﻿using CDSysLDManageProject.BYDTableAdapters;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;

namespace CDSysLDManageProject
{
    public partial class Form1 : Form
    {
        //tbl_stageinfoTableAdapter stageinfo = new tbl_stageinfoTableAdapter();
        //tb_RecipeInfoTableAdapter recipeinfo = new tb_RecipeInfoTableAdapter();
        //rt_ProcessInfoTableAdapter processinfo = new rt_ProcessInfoTableAdapter();
        //tbl_LDTaskListTableAdapter task = new tbl_LDTaskListTableAdapter();
        //Insertht_askListTableAdapter inserhttask = new Insertht_askListTableAdapter();
        //ht_LDTaskListTableAdapter httask = new ht_LDTaskListTableAdapter();
        //tbl_stageTrayInfoTableAdapter stagetray = new tbl_stageTrayInfoTableAdapter();
        //tbl_FRDataTableAdapter frdata = new tbl_FRDataTableAdapter();
        //tb_LinePalletTableAdapter lp = new tb_LinePalletTableAdapter();
        BYDMesDAL meddal = new BYDMesDAL();
        DataTable dtspecialprocess = new DataTable();
        static SocketTest st1 = new SocketTest();
        static SocketTest st2 = new SocketTest();
        static SocketTest st3 = new SocketTest();
        static SocketTest st4 = new SocketTest();
        static SocketTest st5 = new SocketTest();

        MySocket iSocket;
        Thread receivethread;//收数线程
        Thread PackPickthread;//分包初解析线程
        static string moudle = "BYD充电";
        List<byte> RecBufferList = new List<byte>();
        CDPackPick packPick;
        KapjinEqProtocol kep ;
        List<StageStatusMod> StageStatus;
        bool hadOutInventory=false;
        bool hadInInventory=false;
        bool HandMode = false;
        string ip1 = System.Configuration.ConfigurationManager.AppSettings["WCSAddress"];
        int port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["WCSPort"]);
        int port1 = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["WCSPort1"]);
        int port2 = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["WCSPort2"]);
        int port3 = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["WCSPort3"]);
        int port4 = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["WCSPort4"]);
        int onway15no = 0;
        int onway19no = 0;
        int autoout = 0;    //是否自动搬出
        int cellstsallowngno = 0;
        public Form1()
        {
            InitializeComponent();
            
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            rt_ProcessInfoTableAdapter processinfo = new rt_ProcessInfoTableAdapter();
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
            this.KeyPreview = true;
            //根据堆垛机是否就位来控制ECS的销钉
            LoadXMLFile(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase);
            tbxeqsts.Text = "待机中";
            tbxeqsts.BackColor = Color.SpringGreen;
            //iSocket = new MySocket();
            //st1.CreateClient(ip1, port);
            //st2.CreateClient(ip1, port1);
            //st3.CreateClient(ip1, port2);
            //st4.CreateClient(ip1, port3);
            ////st5.CreateClient(ip1, port4);
            //bginitial.RunWorkerAsync();
            dtspecialprocess = processinfo.GetProcessInfo();
            for (int i = 0; i < dtspecialprocess.Rows.Count; i++)
            {
                listboxstageloc.Items.Add(dtspecialprocess.Rows[i]["kpprocessno"]);
            }
            HandMode = false;
            //bgOutAndInInventory.RunWorkerAsync();
            //bgReplayECS.RunWorkerAsync();
            //bgCreateTask.RunWorkerAsync();
            //bgWriteLog.RunWorkerAsync();
            //bgReplayForkSts.RunWorkerAsync();
            //bgFreshStageSts.RunWorkerAsync();
            ///////bgSlave.RunWorkerAsync();


        }

        /// <summary>
        /// 接收
        /// </summary>
        private void receiveByte()
        {
            try
            {
                while (true)
                {
                  int reclength =  iSocket.SocketReceive(RecBufferList);
                  if (reclength < 1)
                  {
                      Thread.Sleep(1000);
                  }
                  else
                  {
                      string str1 = "";
                  }
                }
            }
            catch (Exception ex)
            {
                Exceptionlog.InsertException(ex);

            }
        }

        private void BufferPackPick()
        {
           
                while (true)
                {
                    try
                    {
                        packPick.bufferHandle(RecBufferList);
                    }
                     catch (Exception ex)
                     {
                         Exceptionlog.InsertException(ex);

                     }
                }
          
        }

        private void bgwAliveSignal_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                try
                {
                    if (!kep.AliveSignal())
                    {
                        Exceptionlog.InsertException("心跳超时", "与电源通讯的心跳超时，与电源设备的以太网通讯可能发送异常。");
                        tbxeqsts.Text = "与电源通讯异常";
                        tbxeqsts.BackColor = Color.Red;
                        //Thread.Sleep(10000);
                    }
                    else
                    {
                        //Thread.Sleep(5000);
                        if (tbxeqsts.Text == "与电源通讯异常")
                        {
                            tbxeqsts.Text = "";
                            tbxeqsts.BackColor = Color.White;
                        }

                    }
                }
                catch (Exception ex)
                {
                    Exceptionlog.InsertException(ex);
                }

            }
        }

        private void timerSynTime_Tick(object sender, EventArgs e)
        {
            timerSynTime.Stop();
            bgSynTime.RunWorkerAsync();
        }

        private void btreqStageStatus_Click(object sender, EventArgs e)
        {

            StageStatus=kep.SynStageStatus();
            //tbavaliableStage.Text = StageStatus[0].Stagelocation;

        }



        private void bg_DoWork(object sender, DoWorkEventArgs e)
        {

            while (true)
            {
                if (GParam.RecListDic.ContainsKey("ERD") && GParam.RecStringDic.ContainsKey("ERD") && GParam.RecStringDic["ERD"].Length > 0)
                {
                    //richtbxmsg.AppendText("已收到充放电结果\r\n");
                    //    //Thread.Sleep(200);
                    //bool flag = kep.StepResult();
                    //if (flag == true)
                    //{

                    //}
                    //else
                    //{
                    //    richtbxmsg.AppendText("回复ECS充电完成失败！可能是由于数据解析错误导致的\r\n");
                    //    Log.SystemError.Add("回复ECS充电完成失败！可能是由于数据解析错误导致的");
                    //    Thread.Sleep(500);
                    //}
                    if (bgReplyERD.IsBusy)
                    {

                    }
                    else
                    {
                        bgReplyERD.RunWorkerAsync();
                    }
                }
              


                if (GParam.RecListDic.ContainsKey("EPF") && GParam.RecStringDic.ContainsKey("EPF") && GParam.RecStringDic["EPF"].Length > 0)
                {
                    //richtbxmsg.AppendText("已收到充电完成信号\r\n");
                    ////tbmsg.BackColor = Color.Yellow;
                    //LoadXMLFile(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase);
                    //List<string> outInventory = kep.ProcessFinish();

                    //if (outInventory.Count > 0)
                    //{
                    //    //生成出库任务
                    //    CreateOutTask(outInventory);


                    //}
                    //else
                    //{
                    //    while (outInventory.Count < 1)
                    //    {
                    //        outInventory = kep.ProcessFinish();
                    //    }
                    //    richtbxmsg.AppendText("回复充电完成信号异常\r\n");
                    //    Log.SystemError.Add("回复充电完成信号出现异常，可能是网络异常导致的");

                    //    //Thread.Sleep(500);

                    //}
                    if (bgReplyEPF.IsBusy)
                    {

                    }
                    else
                    {
                        bgReplyEPF.RunWorkerAsync();
                    }

                }
                if (GParam.RecListDic.ContainsKey("ERS") && GParam.RecStringDic.ContainsKey("ERS") && GParam.RecStringDic["ERS"].Length > 0)
                {
                    //List<Dictionary<string, string>> listlocationsts=kep.StageStatusChanged();
                    
                    //for (int i=0;i<listlocationsts.Count;i++)
                    //{
                    //    string stagelocation=listlocationsts[i].Keys.ToList<string>()[0];
                    //    string status=listlocationsts[i].Values.ToList<string>()[0];
                    //    UpdateStageStatus(stagelocation, status);
                    //    listlocationsts.RemoveAt(0);
                    //}
                    if (bgReplyERS.IsBusy)
                    {
                    }
                    else
                    {
                        bgReplyERS.RunWorkerAsync();
                    }
                 
                }

                if (GParam.RecListDic.ContainsKey("ESC") && GParam.RecStringDic.ContainsKey("ESC") && GParam.RecStringDic["ESC"].Length > 0)
                {

                   
                    kep.RequestStackerCraneStatus();
                    GParam.RecStringDic["ESC"] = "";
                   
                }

             
                Thread.Sleep(500);
            }
        }


        //创建或获取XML的配置文件的地址
        public void LoadXMLFile(string path)
        {



            XmlDocument xmlDoc = new XmlDocument();
            string XMLPath = path;
            XMLPath = XMLPath + "ArugmentSetting.xml";
            //如果不存在导出路径XML的话则创建。
            if (!File.Exists(XMLPath))
            {
                //创建类型声明节点  
                XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
                xmlDoc.AppendChild(node);
                //创建根节点  

                XmlNode root = xmlDoc.CreateElement("参数");
                xmlDoc.AppendChild(root);
                string SysPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                CreateNode(xmlDoc, root, "是否自动搬出", "1");
                CreateNode(xmlDoc, root, "允许NG个数", "0");

                try
                {
                    XMLPath = path;
                    XMLPath = XMLPath + "\\" + "ArugmentSetting.xml";
                    xmlDoc.Save(XMLPath);
                    return;
                }
                catch (Exception e)
                {
                    //显示错误信息  
                    Console.WriteLine(e.Message);
                }

            }
            else
            {
                XMLPath = path + "\\" + "ArugmentSetting.xml";
                xmlDoc.Load(XMLPath);
                //获取某个节点
                XmlNode AutoOut = xmlDoc.SelectSingleNode("参数").SelectSingleNode("是否自动搬出");
                XmlNode AllowNgNo = xmlDoc.SelectSingleNode("参数").SelectSingleNode("允许NG个数");

                cellstsallowngno = int.Parse(AllowNgNo.InnerText);
                if (AutoOut.InnerText == "1")
                {
                    autoout = 1;
                }
                else
                {
                    autoout = 0;
                }


            }
            return;

        }


        public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value)
        {
            XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
            node.InnerText = value;
            parentNode.AppendChild(node);
        }

     


         public bool CreateOutTask (List<string > list)
        {
            ht_LDTaskListTableAdapter httask = new ht_LDTaskListTableAdapter();
            tbl_LDTaskListTableAdapter task = new tbl_LDTaskListTableAdapter();
            tbl_FRDataTableAdapter frdata = new tbl_FRDataTableAdapter();
            List<string> liststr=new List<string>();
            DataTable dtoutlist = new DataTable();

            liststr = list;
            string trayno = "";
            string fromx = "";
            string froml = "";
            string fromc = "";
            string tox = "";
            string tol = "";
            string toc = "";
            for (int i = 0; i < liststr.Count; i++)
            {
                DataTable dttrayno=new DataTable();
                try
                {
                    dttrayno = httask.GetTrayNoFromHtTask(liststr[0].ToString());
                }
                catch (Exception ex)
                {
                    Log.SystemError.Add("获取托盘编号失败,原因是:" + ex.ToString());
                }
                

                if (dttrayno.Rows.Count>0)
                {
                    trayno = dttrayno.Rows[0]["trayno"].ToString();
                }else
                {
                    continue;
                }
                string traytype = trayno.Substring(trayno.Length - 3, 3);
                string recipeid = GetRecipeID(traytype);
                if (string.IsNullOrEmpty(recipeid))
                {
                    richtbxmsg.AppendText("请设置正确的托盘类型对应的配方号\r\n");
                    continue;
                }

                short actionid = 120;   //待定
                short actiontype = 4;
                short priority = 7;

                string usr = "a001";
                string fromlocation = liststr[i];
                fromx = fromlocation.Substring(0, 3);
                froml = fromlocation.Substring(3, 3);
                fromc = fromlocation.Substring(6, 3);
                string tolocation = "001009003";

                tox = tolocation.Substring(0, 3);
                tol = tolocation.Substring(3, 3);
                toc = tolocation.Substring(6, 3);

                int cellstsngcount = int.Parse(frdata.GetCellNGCountByTrayNo(trayno).ToString());

                try
                {
                    dtoutlist = task.GetOutTaskByTrayAndLocation(trayno, fromlocation, tolocation);
                    if (dtoutlist.Rows.Count > 0)
                    {

                    }
                    else
                    {
                        if (cellstsngcount <= cellstsallowngno)
                        {
                            //根据是否搬出参设定来选择是否设置自动搬出，autoout=1，则搬出任务=0，autoout=0，则搬出任务=1即锁定。
                            if (autoout == 1)
                            {
                                task.InsertTask(trayno, recipeid, actionid, actiontype, fromlocation, fromx, froml, fromc, tolocation, tox, tol, toc, priority, null, "m", usr, DateTime.Now, null, null, null, 0);
                            }

                            else
                            {
                                task.InsertTask(trayno, recipeid, actionid, actiontype, fromlocation, fromx, froml, fromc, tolocation, tox, tol, toc, priority, null, "m", usr, DateTime.Now, null, null, null, 1);
                            }
                        }
                        else
                        {
                            
                        }
                        
                        
                        
                    }     
                }
                catch (Exception ex)
                {
                    richtbxmsg.AppendText("生成充放电完成的出库任务失败\r\n");
                    
                    //Log.WriteLog(LogFile.SystemError, trayno + "生成充放电完成的出库任务失败");
                    Log.SystemError.Add("生成充放电完成的出库任务失败"+ex.ToString());
                    continue;
                }
            }

            return true;
        
        }
       


       

        
        public string ReadRightValue(string  eqadr, int eqno, string expectvalue)
        {
            int ngcount = 1;
            string recvalue = "";

            if (expectvalue != "notnull")
            {
                while (ngcount <= 3 && recvalue != expectvalue)
                {
                    if (st1.Connected() == false)
                    {
                        richtbxmsg.AppendText("网络连接断开\r\n");
                         
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st1.Connected() == false)
                        {
                            ReConnect();
                        }

                    }
                    else if (st1.Connected() == true)
                    {
                        bool rdflag = st1.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }

                        Thread.Sleep(200);
                        recvalue = st1.receivedata(eqno, "r");
                        ngcount++;

                    }


                }
            }
            else
            {
                while (ngcount <= 3 && recvalue == "")
                {
                    if (st1.Connected() == false)
                    {
                        richtbxmsg.AppendText("网络连接断开\r\n");
                         
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st1.Connected() == false)
                        {
                            ReConnect();
                        }
                    }
                    else if (st1.Connected())
                    {
                        bool rdflag = st1.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }
                        Thread.Sleep(200);
                        recvalue = st1.receivedata(eqno, "r");
                        ngcount++;
                    }

                }
            }

            //Thread.Sleep(200);
            return recvalue;

        }



        //校验并发送读指令
        public string ReadRightValue2(string eqadr, int eqno, string expectvalue)
        {
            int ngcount = 1;
            string recvalue = "";

            if (expectvalue != "notnull")
            {
                while (ngcount <= 3 && recvalue != expectvalue)
                {
                    if (st2.Connected() == false)
                    {
                        //richtbxmsg.AppendText("网络连接断开");
                        richtbxmsg.AppendText("网络连接断开\r\n");
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st2.Connected() == false)
                        {
                            ReConnect2();
                        }

                    }
                    else if (st2.Connected() == true)
                    {
                        bool rdflag = st2.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }
                        else
                        {
                            Thread.Sleep(100);
                            recvalue = st2.receivedata(eqno, "r");
                            ngcount++;

                        }


                    }


                }
            }
            else
            {
                while (ngcount <= 3 && recvalue == "")
                {
                    if (st2.Connected() == false)
                    {
                        //richtbxmsg.AppendText("网络连接断开");
                        richtbxmsg.AppendText("网络连接断开\r\n");
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st2.Connected() == false)
                        {
                            ReConnect2();
                        }
                    }
                    else if (st2.Connected())
                    {
                        bool rdflag = st2.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }
                        Thread.Sleep(200);
                        recvalue = st2.receivedata(eqno, "r");
                        ngcount++;
                    }

                }
            }

            //Thread.Sleep(200);
            return recvalue;

        }


        //校验并发送读指令
        public string ReadRightValue3(string eqadr, int eqno, string expectvalue)
        {
            int ngcount = 1;
            string recvalue = "";

            if (expectvalue != "notnull")
            {
                while (ngcount <= 3 && recvalue != expectvalue)
                {
                    if (st3.Connected() == false)
                    {
                        //richtbxmsg.AppendText("网络连接断开");
                        richtbxmsg.AppendText("网络连接断开\r\n");
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st3.Connected() == false)
                        {
                            ReConnect3();
                        }

                    }
                    else if (st3.Connected() == true)
                    {
                        bool rdflag = st3.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }

                        Thread.Sleep(100);
                        recvalue = st3.receivedata(eqno, "r");
                        ngcount++;
                    }


                }
            }
            else
            {
                while (ngcount <= 3 && recvalue == "")
                {
                    if (st3.Connected() == false)
                    {
                        //richtbxmsg.AppendText("网络连接断开");
                        richtbxmsg.AppendText("网络连接断开\r\n");
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st3.Connected() == false)
                        {
                            ReConnect3();
                        }
                    }
                    else if (st3.Connected())
                    {
                        bool rdflag = st3.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }
                        Thread.Sleep(200);
                        recvalue = st3.receivedata(eqno, "r");
                        ngcount++;
                    }

                }
            }

            //Thread.Sleep(200);
            return recvalue;

        }



        //校验并发送读指令
        public string ReadRightValue4(string eqadr, int eqno, string expectvalue)
        {
            int ngcount = 1;
            string recvalue = "";

            if (expectvalue != "notnull")
            {
                while (ngcount <= 3 && recvalue != expectvalue)
                {
                    if (st4.Connected() == false)
                    {
                        //richtbxmsg.AppendText("网络连接断开");
                        richtbxmsg.AppendText("网络连接断开\r\n");
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st4.Connected() == false)
                        {
                            ReConnect4();
                        }

                    }
                    else if (st4.Connected() == true)
                    {
                        bool rdflag = st4.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }

                        Thread.Sleep(100);
                        recvalue = st4.receivedata(eqno, "r");
                        ngcount++;
                    }


                }
            }
            else
            {
                while (ngcount <= 3 && recvalue == "")
                {
                    if (st4.Connected() == false)
                    {
                        //richtbxmsg.AppendText("网络连接断开");
                        richtbxmsg.AppendText("网络连接断开\r\n");
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st4.Connected() == false)
                        {
                            ReConnect4();
                        }
                    }
                    else if (st4.Connected())
                    {
                        bool rdflag = st4.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }
                        Thread.Sleep(200);
                        recvalue = st4.receivedata(eqno, "r");
                        ngcount++;
                    }

                }
            }

           // Thread.Sleep(200);
            return recvalue;

        }


        //校验并发送读指令
        public string ReadRightValue5(string eqadr, int eqno, string expectvalue)
        {
            int ngcount = 1;
            string recvalue = "";

            if (expectvalue != "notnull")
            {
                while (ngcount <= 3 && recvalue != expectvalue)
                {
                    if (st5.Connected() == false)
                    {
                        //richtbxmsg.AppendText("网络连接断开");
                        richtbxmsg.AppendText("网络连接断开\r\n");
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st5.Connected() == false)
                        {
                            ReConnect5();
                        }

                    }
                    else if (st5.Connected() == true)
                    {
                        bool rdflag = st5.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }

                        Thread.Sleep(100);
                        recvalue = st5.receivedata(eqno, "r");
                        ngcount++;
                    }


                }
            }
            else
            {
                while (ngcount <= 3 && recvalue == "")
                {
                    if (st5.Connected() == false)
                    {
                        //richtbxmsg.AppendText("网络连接断开");
                        richtbxmsg.AppendText("网络连接断开\r\n");
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st5.Connected() == false)
                        {
                            ReConnect5();
                        }
                    }
                    else if (st5.Connected())
                    {
                        bool rdflag = st5.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }
                        Thread.Sleep(200);
                        recvalue = st5.receivedata(eqno, "r");
                        ngcount++;
                    }

                }
            }

            // Thread.Sleep(200);
            return recvalue;

        }

        //校验并发送读指令
        public  string ReadRightValueForSlave(string eqadr, int eqno, string expectvalue)
        {
            int ngcount = 1;
            string recvalue = "";

            if (expectvalue != "notnull")
            {
                while (ngcount <= 3 && recvalue != expectvalue)
                {
                    if (st5.Connected() == false)
                    {
                        //richtbxmsg.AppendText("网络连接断开");
                        richtbxmsg.AppendText("网络连接断开\r\n");
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st5.Connected() == false)
                        {
                            ReConnectForSlave();
                        }

                    }
                    else if (st5.Connected() == true)
                    {
                        bool rdflag = st5.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }

                        Thread.Sleep(100);
                        recvalue = st5.receivedata(eqno, "r");
                        ngcount++;
                    }


                }
            }
            else
            {
                while (ngcount <= 3 && recvalue == "")
                {
                    if (st5.Connected() == false)
                    {
                        //richtbxmsg.AppendText("网络连接断开");
                        richtbxmsg.AppendText("网络连接断开\r\n");
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st5.Connected() == false)
                        {
                            ReConnect5();
                        }
                    }
                    else if (st5.Connected())
                    {
                        bool rdflag = st5.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }
                        Thread.Sleep(200);
                        recvalue = st5.receivedata(eqno, "r");
                        ngcount++;
                    }

                }
            }

            // Thread.Sleep(200);
            return recvalue;

        }



        //校验并发送写指令
        public void WriteRightValue(int eqadr, int eqno, int value)
        {
            int ngcount = 1;
            string recvalue = "";
            bool sendflag = false;

            while (sendflag != true)
            {
                if (st1.Connected() == false)
                {
                    //richtbxmsg.AppendText("网络连接断开");
                    richtbxmsg.AppendText("网络连接断开\r\n");
                    //WriteLogTxt(DateTime.Now + " 网络连接断开");
                    while (st1.Connected() == false)
                    {
                        ReConnect();
                    }

                }
                else if (st1.Connected())
                {
                    sendflag = st1.sendWrdata(eqadr, eqno, value);
                    if (!sendflag)
                    {
                        //WriteLogTxt(DateTime.Now + "  " + eqadr + "寄存器写" + value + "失败");

                    }
                    Thread.Sleep(100);
                    recvalue = st1.receivedata(1, "w");
                    ngcount++;

                }

            }
            //Thread.Sleep(200);

        }


        //校验并发送写指令
        public void WriteRightValue2(int  eqadr, int eqno, int value)
        {
            int ngcount = 1;
            string recvalue = "";
            bool sendflag = false;

            while (sendflag != true)
            {
                if (st2.Connected() == false)
                {
                    richtbxmsg.AppendText("网络连接断开\r\n");
                     
                    //WriteLogTxt(DateTime.Now + " 网络连接断开");
                    while (st2.Connected() == false)
                    {
                        ReConnect2();
                    }

                }
                else if (st2.Connected())
                {
                    sendflag = st2.sendWrdata(eqadr, eqno, value);
                    if (!sendflag)
                    {
                        //WriteLogTxt(DateTime.Now + "  " + eqadr + "寄存器写" + value + "失败");

                    }
                    else
                    {
                        Thread.Sleep(100);
                        recvalue = st2.receivedata(1, "w");
                        ngcount++;

                    }

                }

            }
           // Thread.Sleep(200);

        }


        //校验并发送写指令
        public void WriteRightValue3(int eqadr, int eqno, int value)
        {
            int ngcount = 1;
            string recvalue = "";
            bool sendflag = false;

            while (sendflag != true)
            {
                if (st3.Connected() == false)
                {
                    richtbxmsg.AppendText("网络连接断开\r\n");

                    //WriteLogTxt(DateTime.Now + " 网络连接断开");
                    while (st3.Connected() == false)
                    {
                        ReConnect3();
                    }

                }
                else if (st3.Connected())
                {
                    sendflag = st3.sendWrdata(eqadr, eqno, value);
                    if (!sendflag)
                    {
                        //WriteLogTxt(DateTime.Now + "  " + eqadr + "寄存器写" + value + "失败");

                    }
                    Thread.Sleep(100);
                    recvalue = st3.receivedata(1, "w");
                    ngcount++;

                }

            }
            //Thread.Sleep(200);

        }


        //校验并发送写指令
        public void WriteRightValue4(int eqadr, int eqno, int value)
        {
            int ngcount = 1;
            string recvalue = "";
            bool sendflag = false;

            while (sendflag != true)
            {
                if (st4.Connected() == false)
                {
                    richtbxmsg.AppendText("网络连接断开\r\n");

                    //WriteLogTxt(DateTime.Now + " 网络连接断开");
                    while (st4.Connected() == false)
                    {
                        ReConnect4();
                    }

                }
                else if (st4.Connected())
                {
                    sendflag = st4.sendWrdata(eqadr, eqno, value);
                    if (!sendflag)
                    {
                        //WriteLogTxt(DateTime.Now + "  " + eqadr + "寄存器写" + value + "失败");

                    }
                    Thread.Sleep(100);
                    recvalue = st4.receivedata(1, "w");
                    ngcount++;

                }

            }
            //Thread.Sleep(200);

        }


        //校验并发送写指令
        public void WriteRightValue5(int eqadr, int eqno, int value)
        {
            int ngcount = 1;
            string recvalue = "";
            bool sendflag = false;

            while (sendflag != true)
            {
                if (st5.Connected() == false)
                {
                    richtbxmsg.AppendText("网络连接断开\r\n");

                    //WriteLogTxt(DateTime.Now + " 网络连接断开");
                    while (st5.Connected() == false)
                    {
                        ReConnect5();
                    }

                }
                else if (st5.Connected())
                {
                    sendflag = st5.sendWrdata(eqadr, eqno, value);
                    if (!sendflag)
                    {
                        //WriteLogTxt(DateTime.Now + "  " + eqadr + "寄存器写" + value + "失败");

                    }
                    Thread.Sleep(100);
                    recvalue = st5.receivedata(1, "w");
                    ngcount++;

                }

            }
            //Thread.Sleep(200);

        }


       

        //校验并发送写指令
        public  void WriteRightValueForSlave(string eqadr, int eqno, string value)
        {
            int ngcount = 1;
            string recvalue = "";
            bool sendflag = false;

            while (sendflag != true)
            {
                if (st5.Connected() == false)
                {
                    richtbxmsg.AppendText("网络连接断开\r\n");
                    //WriteLogTxt(DateTime.Now + " 网络连接断开");
                    while (st5.Connected() == false)
                    {
                        ReConnectForSlave();
                    }

                }
                else if (st5.Connected())
                {
                    sendflag = st5.sendWrdataForSlave(eqadr, eqno, value);
                    if (!sendflag)
                    {
                        //WriteLogTxt(DateTime.Now + "  " + eqadr + "寄存器写" + value + "失败");

                    }
                    Thread.Sleep(100);
                    recvalue = st5.receivedata(1, "w");
                    ngcount++;

                }

            }
            //Thread.Sleep(200);

        }


        //连接网络
        private void ReConnect()
        {
            richtbxmsg.AppendText("与堆垛机网络连接中断1\r\n");
            if (!st1.Connected())
            {
                try
                {
                    st1.CreateClient(ip1, port);
                }
                catch (Exception)
                {


                }

            }
            else
            {

                richtbxmsg.AppendText("与堆垛机网络连接恢复\r\n");
                 
                return;
            }
        }



        //连接网络
        private void ReConnect2()
        {
            richtbxmsg.AppendText("与堆垛机网络连接中断2\r\n");
            if (!st2.Connected())
            {
                try
                {
                    st2.CreateClient(ip1, port1);
                }
                catch (Exception)
                {

                }

            }
            else
            {

                richtbxmsg.AppendText("与堆垛机连接恢复\r\n");

                return;
            }
        }


        //连接网络
        private void ReConnect3()
        {
            if (!st3.Connected())
            {
                richtbxmsg.AppendText("与堆垛机网络连接中断3\r\n");
                try
                {
                    st3.CreateClient(ip1, port2);
                }
                catch (Exception)
                {

                }

            }
            else
            {

                richtbxmsg.AppendText("与堆垛机网络连接恢复\r\n");
                return;
            }
        }

        //连接网络
        private void ReConnect4()
        {
            if (!st4.Connected())
            {
                richtbxmsg.AppendText("与堆垛机网络连接中断4\r\n");
                try
                {
                    st4.CreateClient(ip1, port3);
                }
                catch (Exception)
                {

                }

            }
            else
            {

                richtbxmsg.AppendText("与堆垛机网络连接恢复\r\n");
                return;
            }
        }


        //连接网络PLC PORT1014
        private void ReConnect5()
        {
            if (!st5.Connected())
            {
                richtbxmsg.AppendText("与堆垛机网络连接中断5\r\n");
                try
                {
                    st5.CreateClient(ip1, port4);
                }
                catch (Exception)
                {

                }

            }
            else
            {

                richtbxmsg.AppendText("与堆垛机网络连接恢复5\r\n");
                return;
            }
        }

        //连接网络PLC PORT1014
        private void ReConnectForSlave()
        {
            if (!st5.Connected())
            {
                richtbxmsg.AppendText("与堆垛机网络连接中断5\r\n");
                try
                {
                    st5.CreateClient(ip1, port4);
                }
                catch (Exception)
                {

                }

            }
            else
            {

                richtbxmsg.AppendText("与堆垛机网络连接恢复5\r\n");
                return;
            }
        }


        private void bgBeginProcess_DoWork(object sender, DoWorkEventArgs e)
        {
            tbl_LDTaskListTableAdapter task = new tbl_LDTaskListTableAdapter();
            string fromx="";
            string froml="";
            string fromc="";
            string tox="";
            string tol="";
            string toc="";
            string TrayNo="";
            string TaskType="";
            bool checknull = true;
            bool outnull = true;
            int ActionType=0 ;
            int keyid;
            hadInInventory = false;
            hadOutInventory = false;
            //此线程一直启动，负责搬送托盘
            while(true)
            {
                
                DataTable dttask=new DataTable();

                if (HandMode == true)
                {
                    continue;
                }
                try
                {
                    
                    if (ReadRightValue("1526", 1, "notnull")=="0000")
                    {
                        checknull=true;
                    }
                    
                    if (ReadRightValue("1523", 1, "notnull")== "0000")
                    {
                        outnull = true;
                    }
                    if (checknull == true && outnull == true)
                    {
                        dttask = task.GetTaskInfo();
                    }
                    else if (checknull == false)
                    {
                        dttask = task.GetTaskByCheckAndOutSts("001009002");
                    }
                    else if (outnull == false)
                    {
                        dttask = task.GetTaskByCheckAndOutSts("001009003");
                    }
                    else if (checknull == false && outnull == false)
                    {
                        dttask = task.GetTaskByNoCheckAndOut("001009003", "001009002");
                    }
                    
                }
                catch (Exception ex)
                {
                    richtbxmsg.AppendText("从服务器获取任务失败\r\n");
                    Log.SystemError.Add("从服务器获取任务失败"+ex.ToString());
                }
                
                if (dttask.Rows.Count > 0)
                {

                    fromx = "";
                    froml = "";
                    fromc = "";
                    tox = "";
                    tol = "";
                    toc = "";
                    TrayNo = "";
                    hadInInventory = false;
                    hadOutInventory = false;

                    DataRow[] dr = dttask.Select();
                    keyid = int.Parse(dr[0]["keyid"].ToString());
                    TrayNo = dr[0]["trayno"].ToString();
                    fromx = dr[0]["fromseries"].ToString();
                    froml = dr[0]["fromcolumn"].ToString();
                    fromc = dr[0]["fromrow"].ToString();

                    tox = dr[0]["toseries"].ToString();
                    tol = dr[0]["tocolumn"].ToString();
                    toc = dr[0]["torow"].ToString();
                    ActionType = int.Parse(dr[0]["tasktype"].ToString());
                    Log.Trace.Add("堆垛机当前任务是将"+TrayNo+"搬送到"+tox+tol+toc);
                   
                }else
                {
                    Thread.Sleep(1000);
                    continue;
                }
                string rec506 = ReadRightValue("506", 1, "0001");
                if (rec506 != "0001")
                {
                   
                    richtbxmsg.AppendText("堆垛机现在非空闲状态" + TrayNo + "搬送失败\r\n");
                    //Log.SystemError.Add("堆垛机上次非正常结束，" + TrayNo + "搬送失败");
                    Thread.Sleep(5000);
                    continue;
                }
                if (ActionType == 4)
                {
                    if (tol == "009" && toc == "002")
                    {
                        string checkflag = ReadRightValue("1526", 1, "notnull");
                        if (checkflag == "0001")
                        {
                            richtbxmsg.AppendText("警告！校正托盘架台被占用，请清理校正架台的非校正托盘\r\n");
                            //校验架台被占用
                            checknull = false;
                            continue;
                        }
                        else
                        {
                           
                            RemoveTrayProcess(TrayNo, fromx, froml, fromc, tox, tol, toc, keyid, ActionType);
                            checknull = true;
                        }
                    }
                    else if (tol == "009" && toc == "003")
                    {
                        string outflag = ReadRightValue("1523", 1, "notnull");
                        if (outflag == "0001")
                        {
                            richtbxmsg.AppendText("警告！出库架台被占用中，请及时处理出库架台\r\n");
                            //出库架台被占用
                            outnull = false;
                            continue;
                        }
                        else
                        {
                            
                            RemoveTrayProcess(TrayNo, fromx, froml, fromc, tox, tol, toc, keyid, ActionType);
                            outnull = true;
                        }
                    }
                    else
                    {
                        RemoveTrayProcess(TrayNo, fromx, froml, fromc, tox, tol, toc, keyid, ActionType);
                    }
                    
                }
                else if (ActionType == 5)
                {
                    FireProcess(fromx, froml, fromc, tox, tol, toc, keyid, ActionType);
                }
                

            }

            
        }
        //火灾流程
        public void FireProcess(string fromx, string froml, string fromc, string tox, string tol, string toc, int keyid, int ActionType)
        {
            Insertht_askListTableAdapter inserhttask = new Insertht_askListTableAdapter();
            tbl_LDTaskListTableAdapter task = new tbl_LDTaskListTableAdapter();
            //锁定任务
            task.UpdateIsLockSts(keyid);

            //动作指示ID
            WriteRightValue(30, 1, 6);

            WriteRightValue(31, 1, ActionType);

            //From 
            WriteRightValue(32, 1, int.Parse(fromx));
            WriteRightValue(33, 1, int.Parse(froml));
            WriteRightValue(34, 1, int.Parse(fromc));

            ////To的值
            //WriteRightValue(35, 1, int.Parse(tox));
            //WriteRightValue(36, 1, int.Parse(tol));
            //WriteRightValue(37, 1, int.Parse(toc));

            //更新
            WriteRightValue(10, 1, 1);

            WriteRightValue(100, 1, 1);
            //等待W0510是否置1

            string rec510 = ReadRightValue("510", 1, "0001");

            if (rec510 != "0001")
            {

                Log.SystemError.Add("PLCW510响应异常");
                richtbxmsg.AppendText("PLCW510响应异常\r\n");
                return;
            }
            WriteRightValue(10, 1, 0);
            //richtbxmsg.AppendText("正在移动\r\n");
            tbxeqsts.Text = "移动火灾架台中";
            tbxeqsts.BackColor = Color.Yellow;
            string ldstatus = "";

            while (ReadRightValue("511", 1, "notnull") != "0001")
            {      

                string rec590 = ReadRightValue("590", 1, "notnull");
               
                string rec591 = ReadRightValue("591", 1, "notnull");
               
                string rec592 = ReadRightValue("592", 1, "notnull");
                tbxeqloc.Text = rec590.Substring(3, 1) +"-"+ rec591.Substring(3, 1) +"-"+ rec592.Substring(3, 1);
                //Log.Trace.Add("堆垛机当前位置是" + rec590.Substring(3, 1) + "-" + rec591.Substring(3, 1) + "-" + rec592.Substring(3, 1));
                ldstatus = ReadRightValue("506", 1, "notnull");

                if (ldstatus == "000A")
                {
                  
                    tbxeqsts.Text = "火灾运行中";
                    tbxeqsts.BackColor = Color.Yellow;

                }
                else if (ldstatus == "000B")
                {
                  
                    tbxeqsts.Text = "喷射待机中";
                    tbxeqsts.BackColor = Color.Yellow;
                }

            } 
            WriteRightValue(11, 1, 1);
            if (ReadRightValue("511", 1, "0000") == "0000")
            {
                WriteRightValue(11, 1, 0);
              
            }
            string rec560 = ReadRightValue("560", 1, "0006");
            string rec561 = ReadRightValue("561", 1, ActionType.ToString().PadLeft(4, '0'));

            string rec562 = ReadRightValue("562", 1, fromx.PadLeft(4, '0'));
            string rec563 = ReadRightValue("563", 1, froml.PadLeft(4, '0'));
            string rec564 = ReadRightValue("564", 1, fromc.PadLeft(4, '0'));

            string rec565 = ReadRightValue("565", 1, tox.PadLeft(4, '0'));
            string rec566 = ReadRightValue("566", 1, tol.PadLeft(4, '0'));
            string rec567 = ReadRightValue("567", 1, toc.PadLeft(4, '0'));

            string endcode = ReadRightValue("568", 1, "notnull");
            short endtype = 1;

            if (endcode == "0001")
            {
                endtype = 0;
                if (rec560 == "0006" && rec561 == ActionType.ToString().PadLeft(4, '0') && rec562 == fromx.PadLeft(4, '0') && rec563 == froml.PadLeft(4, '0') && rec564 == fromc.PadLeft(4, '0') && rec565 == tox.PadLeft(4, '0') && rec566 == tol.PadLeft(4, '0') && rec567 == toc.PadLeft(4, '0'))
                {
                    tbxeqsts.Text = "已完成灭火";
                    tbxeqsts.BackColor = Color.SpringGreen;
                    
                }
                else
                {
                    tbxeqsts.Text = "完成任务错误";
                    tbxeqsts.BackColor = Color.Red;
                    Log.SystemError.Add( "堆垛机动作类型和动作ID与之前的不一致");
                }


            }
            else if (endcode == "0002")
            {
               
                tbxeqsts.Text = "堆垛机运行异常";
                tbxeqsts.BackColor = Color.Red;
            }

           
            string str1 = ReadRightValue("506", 1, "notnull");
            while (ReadRightValue("506", 1, "notnull") != "000D")
            {
                string str2=ReadRightValue("506", 1, "notnull");
                if (str2=="000C")
                tbxeqsts.Text = "灭火器喷射中";
                tbxeqsts.BackColor = Color.Yellow;
            }
            tbxeqsts.Text = "灭火器喷射结束";
            tbxeqsts.BackColor = Color.Yellow;
            try
            {
                inserhttask.Insertht_LDTaskList(keyid, short.Parse(endcode), endtype, "a001", DateTime.Now);
            }
            catch (Exception)
            {
                Log.SystemError.Add("将火灾任务存入历史任务表失败");
            }
        }




        //正常自动搬入搬出流程
        public void RemoveTrayProcess(string TrayNo, string fromx, string froml, string fromc, string tox, string tol, string toc, int keyid, int ActionType)
        {
            Insertht_askListTableAdapter inserhttask = new Insertht_askListTableAdapter();
            tbl_LDTaskListTableAdapter task = new tbl_LDTaskListTableAdapter();
            tbxTrayNo.Text = TrayNo;
            tbxFromLocation.Text = fromx + froml + fromc;
            tbxToLocation.Text = tox + tol + toc;

            if (tol != "009")
            {
                UpdateStageTrayInfo(tox + tol + toc, TrayNo);
            }
           

           
            //动作指示ID
            WriteRightValue(30, 1, 6);

            WriteRightValue(31, 1, ActionType);

            //From 
            WriteRightValue(32, 1, int.Parse(fromx));
            WriteRightValue(33, 1, int.Parse(froml));
            WriteRightValue(34, 1, int.Parse(fromc));

            //To的值
            WriteRightValue(35, 1, int.Parse(tox));
            WriteRightValue(36, 1, int.Parse(tol));
            WriteRightValue(37, 1, int.Parse(toc));

             //更新
            WriteRightValue(10, 1, 1);

            WriteRightValue(100, 1, 1);
            //等待W0510是否置1

            string rec510 = ReadRightValue("510", 1, "0001");

            if (rec510 != "0001")
            {
             
              
                Log.SystemError.Add("PLC响应异常,LD待机异常");
                richtbxmsg.AppendText("PLC响应异常,LD待机异常\r\n");
                if (rec510 == "0002")
                {
                    tbxeqsts.Text = "LD待机异常\r\n";
                    tbxeqsts.BackColor = Color.Red;
                }
                else if (rec510 == "0003")
                {
                    tbxeqsts.Text = "LD搬送Data异常";
                    tbxeqsts.BackColor = Color.Red;
                }
                else if (rec510 == "0004")
                {
                    tbxeqsts.Text = "LD装载地I/L异常";
                    tbxeqsts.BackColor = Color.Red;
                }
                else if (rec510 == "0005")
                {
                    tbxeqsts.Text = "LD装载下降地I/L异常";
                    tbxeqsts.BackColor = Color.Red;
                }
                
                WriteRightValue(10, 1, 0);
                return ;
            }

           

            WriteRightValue(10, 1, 0);
            
            tbxeqsts.Text = "正在移动";
            tbxeqsts.BackColor = Color.SpringGreen;
            //锁定任务
            task.UpdateIsLockSts(keyid);
            lb91tray.Text = "";
            string ldstatus = "";

            while (ReadRightValue("511", 1, "notnull") != "0001")
            {       //如果未出库的话才出库
                if (hadOutInventory == false)
                {
                    if (froml == "009" && fromc == "001")
                    {

                        string rec590 = ReadRightValue("590", 1, "notnull");
                       
                        string rec591 = ReadRightValue("591", 1, "notnull");
                        
                        string rec592 = ReadRightValue("592", 1, "notnull");
                        
                        if (rec590 == fromx.PadLeft(4, '0') && rec591 == froml.PadLeft(4, '0') && rec592 == fromc.PadLeft(4, '0'))
                        {
                            tbxeqloc.Text = rec590.Substring(3, 1) + "-" + rec591.Substring(3, 1) + "-" + rec592.Substring(3, 1);
                            WriteRightValue(90, 1, int.Parse(fromx.PadLeft(4, '0')));
                            
                            WriteRightValue(91, 1, int.Parse(froml.PadLeft(4, '0')));
                           
                            WriteRightValue(92, 1, int.Parse(fromc.PadLeft(4, '0')));

                          
                            
                            string rec593 = ReadRightValue("593", 1, "notnull");
                            string rec152A = ReadRightValue("152A", 1, "notnull");

                            if (rec152A == "0001" && rec593 == "0002")
                            {
                              
                                tbxeqsts.Text = "出库已就位";
                                tbxeqsts.BackColor = Color.SpringGreen;
                                WriteRightValue(93, 1, 2);
                              
                                if (ReadRightValue("593", 1, "0000") == "0000")
                                {
                                    WriteRightValue(93, 1, 0);
                                    tbxeqsts.Text = "正在搬送入库";
                                    tbxeqsts.BackColor = Color.SpringGreen;
                                    hadOutInventory = true;
                                }
                                else
                                {
                                    
                                    richtbxmsg.AppendText("PLC异常W0593未复位\r\n");
                                   
                                    Log.SystemError.Add(TrayNo + " W0593未复位");
                                }
                            }
                            else
                            {
                                Log.SystemError.Add("入口销钉下降失败,程序等待中");
                                richtbxmsg.AppendText("入口销钉下降失败,程序等待中\r\n");
                                Thread.Sleep(500);
                            }

                            //
                        }


                    }
                    else if (froml == "009" && fromc == "002")
                    {


                        string rec590 = ReadRightValue("590", 1, "notnull");
                        
                        string rec591 = ReadRightValue("591", 1, "notnull");
                       
                        string rec592 = ReadRightValue("592", 1, "notnull");
                        
                        if (rec590 == fromx.PadLeft(4, '0') && rec591 == froml.PadLeft(4, '0') && rec592 == fromc.PadLeft(4, '0'))
                        {
                            tbxeqloc.Text = rec590.Substring(3, 1) + "-" + rec591.Substring(3, 1) + "-" + rec592.Substring(3, 1);
                            WriteRightValue(90, 1, int.Parse(fromx.PadLeft(4, '0')));
                           
                            WriteRightValue(91, 1, int.Parse(froml.PadLeft(4, '0')));
                            
                            WriteRightValue(92, 1, int.Parse(fromc.PadLeft(4, '0')));
                           

                            
                            string rec593 = ReadRightValue("593", 1, "notnull");
                            string rec152C = ReadRightValue("152C", 1, "notnull");
                            if (rec152C == "0001" && rec593 == "0002")
                            {
                              
                                tbxeqsts.Text = "出库已就位";
                                tbxeqsts.BackColor = Color.SpringGreen;
                                WriteRightValue(93, 1, 2);
                                Thread.Sleep(200);
                                if (ReadRightValue("593", 1, "0000") == "0000")
                                {
                                    WriteRightValue(93, 1, 0);
                                  
                                    tbxeqsts.Text = "正在搬送入库";
                                    tbxeqsts.BackColor = Color.SpringGreen;
                                    hadOutInventory = true;
                                }
                                else
                                {
                                  
                                    richtbxmsg.AppendText("PLC异常W0593未复位\r\n");
                                   
                                    Log.SystemError.Add(TrayNo + " W0593未复位");
                                }
                            }
                            else
                            {
                                Log.SystemError.Add("校验托盘销钉升起失败,程序等待中");
                                richtbxmsg.AppendText("校验托盘销钉升起失败,程序等待中\r\n");
                                Thread.Sleep(500);
                            }

                            //
                        }



                    }
                    

                }
        


                if (hadInInventory == false)
                {
                    if (tol == "009" && toc == "002")
                    {


                        string rec590 = ReadRightValue("590", 1, "notnull");
                       
                        string rec591 = ReadRightValue("591", 1, "notnull");
                        
                        string rec592 = ReadRightValue("592", 1, "notnull");
                        
                      
                        if (rec590 == tox.PadLeft(4, '0') && rec591 == tol.PadLeft(4, '0') && rec592 == toc.PadLeft(4, '0'))
                        {
                            tbxeqloc.Text = rec590.Substring(3, 1) + "-" + rec591.Substring(3, 1) + "-" + rec592.Substring(3, 1);
                            WriteRightValue(90, 1, int.Parse(tox.PadLeft(4, '0')));
                           
                            WriteRightValue(91, 1, int.Parse(tol.PadLeft(4, '0')));
                            
                            WriteRightValue(92, 1, int.Parse(toc.PadLeft(4, '0')));
                           

                            
                            string rec593 = ReadRightValue("593", 1, "notnull");
                            string rec152C = ReadRightValue("152C", 1, "notnull");
                            //判断校验托盘存放位置的销钉是否已经上升。
                            if (rec152C == "0002" && rec593 == "0001")
                            {
                              
                                tbxeqsts.Text = "入库已就位";
                                tbxeqsts.BackColor = Color.SpringGreen;
                                WriteRightValue(93, 1, 1);
                                
                                if (ReadRightValue("593", 1, "0000") == "0000")
                                {
                                    WriteRightValue(93, 1, 0);
                                    hadInInventory = true;
                                    
                                }
                            }
                            else
                            {
                                Log.SystemError.Add("校验托盘位置的销钉升起失败,程序等待中");
                                richtbxmsg.AppendText("校验托盘位置的销钉升起失败,程序等待中\r\n");
                                Thread.Sleep(500);
                            }
                        }


                    }
                    else if (tol == "009" && toc == "003")
                    {


                        string rec590 = ReadRightValue("590", 1, "notnull");
                      
                        string rec591 = ReadRightValue("591", 1, "notnull");
                        
                        string rec592 = ReadRightValue("592", 1, "notnull");
                        
                        if (rec590 == tox.PadLeft(4, '0') && rec591 == tol.PadLeft(4, '0') && rec592 == toc.PadLeft(4, '0'))
                        {
                            tbxeqloc.Text = rec590.Substring(3, 1) + "-" + rec591.Substring(3, 1) + "-" + rec592.Substring(3, 1);
                            WriteRightValue(90, 1, int.Parse(tox.PadLeft(4, '0')));
                           
                            WriteRightValue(91, 1, int.Parse(tol.PadLeft(4, '0')));
                           
                            WriteRightValue(92, 1, int.Parse(toc.PadLeft(4, '0')));

                            
                            string rec593 = ReadRightValue("593", 1, "notnull");
                            string rec152B = ReadRightValue("152B", 1, "notnull");
                            //判断校验托盘存放位置的销钉是否已经上升。
                            if (rec152B == "0002" && rec593 == "0001")
                            {
                                tbxeqsts.Text = "入库已就位";
                                tbxeqsts.BackColor = Color.SpringGreen;
                                WriteRightValue(93, 1, 1);
                                
                                if (ReadRightValue("593", 1, "0000") == "0000")
                                {
                                    WriteRightValue(93, 1, 0);
                                   
                                    hadInInventory = true;
                                    
                                }
                            }
                            else
                            {
                                Log.SystemError.Add("三层出库位置的销钉升起失败,程序等待中");
                                richtbxmsg.AppendText("三层出库位置的销钉升起失败,程序等待中\r\n");
                                Thread.Sleep(500);
                            }
                        }


                    }
                    else if (tol != "009")
                    {

                        string stageloc1 = "";
                        string trayno1 = "";
                        string rec590 = ReadRightValue("590", 1, "notnull");
                       
                        string rec591 = ReadRightValue("591", 1, "notnull");
                        
                        string rec592 = ReadRightValue("592", 1, "notnull");
                       
                      
                        //先验证入库位置是否正确
                        if (rec590 == tox.PadLeft(4, '0') && rec591 == tol.PadLeft(4, '0') && rec592 == toc.PadLeft(4, '0'))
                        {
                            
                            tbxeqsts.Text = "入库已就位";
                            tbxeqloc.Text = rec590.Substring(3, 1) + "-" + rec591.Substring(3, 1) + "-" + rec592.Substring(3, 1);
                            WriteRightValue(90, 1, int.Parse(tox.PadLeft(4, '0')));
                            WriteRightValue(91, 1, int.Parse(tol.PadLeft(4, '0')));
                            WriteRightValue(92, 1, int.Parse(toc.PadLeft(4, '0')));
                           
                            string rec593 = ReadRightValue("593", 1, "0001");
                           
                            if (rec593 == "0001")
                            {
                                Thread.Sleep(700);
                                string stageloc = tox.PadLeft(3, '0') + tol.PadLeft(3, '0') + toc.PadLeft(3, '0');
                                //清空下ETL
                                GParam.RecStringDic["ETL"] = "";
                                for (int i = 0; i < GParam.RecListDic["ETL"].Count; i++)
                                {
                                    GParam.RecListDic["ETL"].RemoveAt(0);
                                }


                                bool flag = kep.TrayLoad(TrayNo, stageloc);
                                bool ETLWrong = false;

                                if (flag == false)
                                {

                                    while (!(GParam.RecListDic.ContainsKey("ETL") && GParam.RecStringDic.ContainsKey("ETL") && GParam.RecStringDic["ETL"].Length > 0 && GParam.RecStringDic["ETL"].Substring(17, 1) == "1"))
                                    {
                                        GParam.RecStringDic["ETL"] = "";
                                        for (int i = 0; i < GParam.RecListDic["ETL"].Count; i++)
                                        {
                                            GParam.RecListDic["ETL"].RemoveAt(0);
                                        }
                                        richtbxmsg.AppendText("托盘由于ECS销钉升起失败，等待人工处理中\r\n");
                                        Log.WriteLog(LogFile.SystemError, TrayNo + "入库升降钉升起失败");

                                        ETLWrong = true;

                                        Thread.Sleep(1000);
                                    }

                                }

                                if (ETLWrong == true)
                                {
                                    //销钉升起成功，即将回复WTL
                                    GParam.RecStringDic["ETL"] = "";
                                     stageloc1 = GParam.RecListDic["ETL"][0].ToString().Substring(8, 9);
                                     trayno1 = "";
                                    DataTable dttaskinfo = new DataTable();
                                    if (stageloc1 == stageloc)
                                    {
                                        dttaskinfo = task.GetTrayNoByToLocation(stageloc);
                                    }
                                    else
                                    {
                                        Log.SystemError.Add("收到的ETL里的架台号与待入库的架台号不符");
                                        dttaskinfo = task.GetTrayNoByToLocation(stageloc1);
                                    }
                                    if (dttaskinfo.Rows.Count > 0)
                                    {
                                        trayno1 = dttaskinfo.Rows[0]["trayno"].ToString();
                                        bool flag1 = kep.TrayLoad(trayno1, stageloc);
                                        if (flag1 == true)
                                        {
                                            richtbxmsg.AppendText("已解除故障，销钉已升起，即将开始充电\r\n");
                                            Log.SystemError.Add("已解除故障，销钉已升起，即将开始充电");

                                            //将架台,托盘信息存储到数据库中
                                            UpdateStageTrayInfo(stageloc, trayno1);
                                            //更新架台显示的托盘号
                                            UpdateStageTrayInfoNull(stageloc, trayno1);
                                        }
                                        else
                                        {
                                            while (flag1 == false)
                                            {
                                                flag1 = kep.TrayLoad(trayno1, stageloc);
                                            }

                                        }
                                    }
                                    else
                                    {
                                        
                                        Log.SystemError.Add("根据架台号：" + stageloc + "查找托盘编号回复ETL失败，当前任务里没有架台对应的托盘信息");
                                    }

                                   

                                }
                                else
                                {

                                }


                                WriteRightValue(93, 1, 1);
                                
                                if (ReadRightValue("593", 1, "0000") == "0000")
                                {
                                    WriteRightValue(93, 1, 0);
                                   
                                    hadInInventory = true;
                                    ShowStageTrayInfo(stageloc, TrayNo);
                                    
                                }


                            }




                        }


                       
                    }

                    Thread.Sleep(200);
                }
            
                ldstatus = ReadRightValue("506", 1, "notnull");
               
                if (ldstatus == "0002")
                {
                    
                    tbxeqsts.Text = "LD运行开始"; 
                    tbxeqsts.BackColor = Color.SpringGreen;
                }
                else if (ldstatus == "0003")
                {
                   
                    tbxeqsts.Text = "LD到达 装载开始"; 
                    tbxeqsts.BackColor = Color.SpringGreen;
                }
                else if (ldstatus == "0004")
                {
                   
                    tbxeqsts.Text = "LD装载下降运行开始"; 
                    tbxeqsts.BackColor = Color.SpringGreen;
                }
                else if (ldstatus == "0005")
                {
                    tbxeqsts.Text = "LD到达 装载下降开始"; 
                    tbxeqsts.BackColor = Color.SpringGreen;
                }
                //这的延迟很有必要！否则会多次重复读取
                Thread.Sleep(200);


            }

            WriteRightValue(11, 1, 1);
            if (ReadRightValue("511", 1, "0000") == "0000")
            {
                WriteRightValue(11, 1, 0);
            }

            if (tol != "009")
            {
                kep.SendTrayInfo(tox.PadLeft(3,'0')+tol.PadLeft(3,'0')+toc.PadLeft(3,'0'),TrayNo,"");
            }
            
            tbxeqsts.Text = "已完成入库";
            tbxeqsts.BackColor = Color.SpringGreen;


            string endcode = ReadRightValue("568", 1, "notnull");
            short endtype = 1;

            if (endcode == "0001")
            {
                endtype = 0;
            }
            else if (endcode == "0002")
            {
               
                tbxeqsts.Text = "堆垛机异常结束";
                tbxeqsts.BackColor = Color.SpringGreen;
            }

            else if (endcode == "0003")
            {
              
                tbxeqsts.Text = "堆垛机运行未结束(无装载)";
                tbxeqsts.BackColor = Color.SpringGreen;
            }

            else if (endcode == "0004")
            {
                
                tbxeqsts.Text = "堆垛机运行未结束(有装载)";
                tbxeqsts.BackColor = Color.SpringGreen;
            }
            tbxeqsts.Text = "待机中";
            try
            {
                inserhttask.Insertht_LDTaskList(keyid, short.Parse(endcode), endtype, "a001", DateTime.Now);
            }
            catch (Exception)
            {
                Log.SystemError.Add(TrayNo + "将任务存入历史任务表失败");
            }
        }



        //手动出库流程
        public void HandOutInventoryProcess(string TrayNo, string fromlocation,string fromx, string froml, string fromc, string tolocation,string tox, string tol, string toc,  short ActionType)
        {
            Insertht_askListTableAdapter inserhttask = new Insertht_askListTableAdapter();
            tbl_LDTaskListTableAdapter task = new tbl_LDTaskListTableAdapter();
            bool hadOutInventory1 = false;
            bool hadInInventory1 = false;
            
            tbxTrayNo.Text = TrayNo;
            tbxFromLocation.Text = fromx + froml + fromc;
            tbxToLocation.Text = tox + tol + toc;

            //动作指示ID
            WriteRightValue(30, 1, 6);

            WriteRightValue(31, 1, ActionType);

            //From 
            WriteRightValue(32, 1, int.Parse(fromx));
            WriteRightValue(33, 1, int.Parse(froml));
            WriteRightValue(34, 1, int.Parse(fromc));

            //To的值
            WriteRightValue(35, 1, int.Parse(tox));
            WriteRightValue(36, 1, int.Parse(tol));
            WriteRightValue(37, 1, int.Parse(toc));

            //更新
            WriteRightValue(10, 1, 1);

            WriteRightValue(100, 1, 1);
            //等待W0510是否置1

            string rec510 = ReadRightValue("510", 1, "0001");

            if (rec510 != "0001")
            {


                Log.SystemError.Add("PLC响应异常,LD待机异常");
                richtbxmsg.AppendText("PLC响应异常,LD待机异常\r\n");
                if (rec510 == "0002")
                {
                    tbxeqsts.Text = "LD待机异常\r\n";
                    tbxeqsts.BackColor = Color.Red;
                }
                else if (rec510 == "0003")
                {
                    tbxeqsts.Text = "LD搬送Data异常";
                    tbxeqsts.BackColor = Color.Red;
                }
                else if (rec510 == "0004")
                {
                    tbxeqsts.Text = "LD装载地I/L异常";
                    tbxeqsts.BackColor = Color.Red;
                }
                else if (rec510 == "0005")
                {
                    tbxeqsts.Text = "LD装载下降地I/L异常";
                    tbxeqsts.BackColor = Color.Red;
                }

                WriteRightValue(10, 1, 0);
                return;
            }



            WriteRightValue(10, 1, 0);

            tbxeqsts.Text = "正在移动";
            tbxeqsts.BackColor = Color.SpringGreen;
            
            lb91tray.Text = "";
            string ldstatus = "";

            while (ReadRightValue("511", 1, "notnull") != "0001")
            {       //如果未出库的话才出库
                if (hadOutInventory1 == false)
                {
                    if (froml == "009" && fromc == "001")
                    {

                        string rec590 = ReadRightValue("590", 1, "notnull");

                        string rec591 = ReadRightValue("591", 1, "notnull");

                        string rec592 = ReadRightValue("592", 1, "notnull");

                        if (rec590 == fromx.PadLeft(4, '0') && rec591 == froml.PadLeft(4, '0') && rec592 == fromc.PadLeft(4, '0'))
                        {
                            tbxeqloc.Text = rec590.Substring(3, 1) + "-" + rec591.Substring(3, 1) + "-" + rec592.Substring(3, 1);
                            WriteRightValue(90, 1, int.Parse(fromx.PadLeft(4, '0')));

                            WriteRightValue(91, 1, int.Parse(froml.PadLeft(4, '0')));

                            WriteRightValue(92, 1, int.Parse(fromc.PadLeft(4, '0')));



                            string rec593 = ReadRightValue("593", 1, "notnull");
                            string rec152A = ReadRightValue("152A", 1, "notnull");

                            if (rec152A == "0001" && rec593 == "0002")
                            {

                                tbxeqsts.Text = "出库已就位";
                                tbxeqsts.BackColor = Color.SpringGreen;
                                WriteRightValue(93, 1, 2);

                                if (ReadRightValue("593", 1, "0000") == "0000")
                                {
                                    WriteRightValue(93, 1, 0);
                                    tbxeqsts.Text = "正在搬送入库";
                                    tbxeqsts.BackColor = Color.SpringGreen;
                                    hadOutInventory = true;
                                }
                                else
                                {

                                    richtbxmsg.AppendText("PLC异常W0593未复位\r\n");

                                    Log.SystemError.Add(TrayNo + " W0593未复位");
                                }
                            }
                            else
                            {
                                Log.SystemError.Add("入口销钉下降失败,程序等待中");
                                richtbxmsg.AppendText("入口销钉下降失败,程序等待中\r\n");
                                Thread.Sleep(500);
                            }

                            //
                        }


                    }
                    else if (froml == "009" && fromc == "002")
                    {


                        string rec590 = ReadRightValue("590", 1, "notnull");

                        string rec591 = ReadRightValue("591", 1, "notnull");

                        string rec592 = ReadRightValue("592", 1, "notnull");

                        if (rec590 == fromx.PadLeft(4, '0') && rec591 == froml.PadLeft(4, '0') && rec592 == fromc.PadLeft(4, '0'))
                        {
                            tbxeqloc.Text = rec590.Substring(3, 1) + "-" + rec591.Substring(3, 1) + "-" + rec592.Substring(3, 1);
                            WriteRightValue(90, 1, int.Parse(fromx.PadLeft(4, '0')));

                            WriteRightValue(91, 1, int.Parse(froml.PadLeft(4, '0')));

                            WriteRightValue(92, 1, int.Parse(fromc.PadLeft(4, '0')));



                            string rec593 = ReadRightValue("593", 1, "notnull");
                            string rec152C = ReadRightValue("152C", 1, "notnull");
                            if (rec152C == "0001" && rec593 == "0002")
                            {

                                tbxeqsts.Text = "出库已就位";
                                tbxeqsts.BackColor = Color.SpringGreen;
                                WriteRightValue(93, 1, 2);
                                Thread.Sleep(200);
                                if (ReadRightValue("593", 1, "0000") == "0000")
                                {
                                    WriteRightValue(93, 1, 0);

                                    tbxeqsts.Text = "正在搬送入库";
                                    tbxeqsts.BackColor = Color.SpringGreen;
                                    hadOutInventory = true;
                                }
                                else
                                {

                                    richtbxmsg.AppendText("PLC异常W0593未复位\r\n");

                                    Log.SystemError.Add(TrayNo + " W0593未复位");
                                }
                            }
                            else
                            {
                                Log.SystemError.Add("校验托盘销钉升起失败,程序等待中");
                                richtbxmsg.AppendText("校验托盘销钉升起失败,程序等待中\r\n");
                                Thread.Sleep(500);
                            }
                        }



                    }


                }



                if (hadInInventory1 == false)
                {
                    if (tol == "009" && toc == "002")
                    {


                        string rec590 = ReadRightValue("590", 1, "notnull");

                        string rec591 = ReadRightValue("591", 1, "notnull");

                        string rec592 = ReadRightValue("592", 1, "notnull");


                        if (rec590 == tox.PadLeft(4, '0') && rec591 == tol.PadLeft(4, '0') && rec592 == toc.PadLeft(4, '0'))
                        {
                            tbxeqloc.Text = rec590.Substring(3, 1) + "-" + rec591.Substring(3, 1) + "-" + rec592.Substring(3, 1);
                            WriteRightValue(90, 1, int.Parse(tox.PadLeft(4, '0')));

                            WriteRightValue(91, 1, int.Parse(tol.PadLeft(4, '0')));

                            WriteRightValue(92, 1, int.Parse(toc.PadLeft(4, '0')));



                            string rec593 = ReadRightValue("593", 1, "notnull");
                            string rec152C = ReadRightValue("152C", 1, "notnull");
                            //判断校验托盘存放位置的销钉是否已经上升。
                            if (rec152C == "0002" && rec593 == "0001")
                            {

                                tbxeqsts.Text = "入库已就位";
                                tbxeqsts.BackColor = Color.SpringGreen;
                                WriteRightValue(93, 1, 1);

                                if (ReadRightValue("593", 1, "0000") == "0000")
                                {
                                    WriteRightValue(93, 1, 0);
                                    hadInInventory = true;

                                }
                            }
                            else
                            {
                                Log.SystemError.Add("校验托盘位置的销钉升起失败,程序等待中");
                                richtbxmsg.AppendText("校验托盘位置的销钉升起失败,程序等待中\r\n");
                                Thread.Sleep(500);
                            }
                        }


                    }
                    else if (tol == "009" && toc == "003")
                    {


                        string rec590 = ReadRightValue("590", 1, "notnull");

                        string rec591 = ReadRightValue("591", 1, "notnull");

                        string rec592 = ReadRightValue("592", 1, "notnull");

                        if (rec590 == tox.PadLeft(4, '0') && rec591 == tol.PadLeft(4, '0') && rec592 == toc.PadLeft(4, '0'))
                        {
                            tbxeqloc.Text = rec590.Substring(3, 1) + "-" + rec591.Substring(3, 1) + "-" + rec592.Substring(3, 1);
                            WriteRightValue(90, 1, int.Parse(tox.PadLeft(4, '0')));

                            WriteRightValue(91, 1, int.Parse(tol.PadLeft(4, '0')));

                            WriteRightValue(92, 1, int.Parse(toc.PadLeft(4, '0')));


                            string rec593 = ReadRightValue("593", 1, "notnull");
                            string rec152B = ReadRightValue("152B", 1, "notnull");
                            //判断校验托盘存放位置的销钉是否已经上升。
                            if (rec152B == "0002" && rec593 == "0001")
                            {
                                tbxeqsts.Text = "入库已就位";
                                tbxeqsts.BackColor = Color.SpringGreen;
                                WriteRightValue(93, 1, 1);

                                if (ReadRightValue("593", 1, "0000") == "0000")
                                {
                                    WriteRightValue(93, 1, 0);

                                    hadInInventory = true;

                                }
                            }
                            else
                            {
                                Log.SystemError.Add("三层出库位置的销钉升起失败,程序等待中");
                                richtbxmsg.AppendText("三层出库位置的销钉升起失败,程序等待中\r\n");
                                Thread.Sleep(500);
                            }
                        }


                    }
                    else if (tol != "009")
                    {

                        string stageloc1 = "";
                        string trayno1 = "";
                        string rec590 = ReadRightValue("590", 1, "notnull");

                        string rec591 = ReadRightValue("591", 1, "notnull");

                        string rec592 = ReadRightValue("592", 1, "notnull");


                        //先验证入库位置是否正确
                        if (rec590 == tox.PadLeft(4, '0') && rec591 == tol.PadLeft(4, '0') && rec592 == toc.PadLeft(4, '0'))
                        {

                            tbxeqsts.Text = "入库已就位";
                            tbxeqloc.Text = rec590.Substring(3, 1) + "-" + rec591.Substring(3, 1) + "-" + rec592.Substring(3, 1);
                            WriteRightValue(90, 1, int.Parse(tox.PadLeft(4, '0')));
                            WriteRightValue(91, 1, int.Parse(tol.PadLeft(4, '0')));
                            WriteRightValue(92, 1, int.Parse(toc.PadLeft(4, '0')));

                            string rec593 = ReadRightValue("593", 1, "0001");

                            if (rec593 == "0001")
                            {
                                Thread.Sleep(700);
                                string stageloc = tox.PadLeft(3, '0') + tol.PadLeft(3, '0') + toc.PadLeft(3, '0');
                                //清空下ETL
                                GParam.RecStringDic["ETL"] = "";
                                for (int i = 0; i < GParam.RecListDic["ETL"].Count; i++)
                                {
                                    GParam.RecListDic["ETL"].RemoveAt(0);
                                }


                                bool flag = kep.TrayLoad(TrayNo, stageloc);
                                bool ETLWrong = false;

                                if (flag == false)
                                {

                                    while (!(GParam.RecListDic.ContainsKey("ETL") && GParam.RecStringDic.ContainsKey("ETL") && GParam.RecStringDic["ETL"].Length > 0 && GParam.RecStringDic["ETL"].Substring(17, 1) == "1"))
                                    {
                                        GParam.RecStringDic["ETL"] = "";
                                        for (int i = 0; i < GParam.RecListDic["ETL"].Count; i++)
                                        {
                                            GParam.RecListDic["ETL"].RemoveAt(0);
                                        }
                                        richtbxmsg.AppendText("托盘由于ECS销钉升起失败，等待人工处理中\r\n");
                                        Log.WriteLog(LogFile.SystemError, TrayNo + "入库升降钉升起失败");

                                        ETLWrong = true;

                                        Thread.Sleep(1000);
                                    }

                                }

                                if (ETLWrong == true)
                                {
                                    //销钉升起成功，即将回复WTL
                                    GParam.RecStringDic["ETL"] = "";
                                    stageloc1 = GParam.RecListDic["ETL"][0].ToString().Substring(8, 9);
                                    trayno1 = "";
                                    DataTable dttaskinfo = new DataTable();
                                    if (stageloc1 == stageloc)
                                    {
                                        dttaskinfo = task.GetTrayNoByToLocation(stageloc);
                                    }
                                    else
                                    {
                                        Log.SystemError.Add("收到的ETL里的架台号与待入库的架台号不符");
                                        dttaskinfo = task.GetTrayNoByToLocation(stageloc1);
                                    }
                                    if (dttaskinfo.Rows.Count > 0)
                                    {
                                        trayno1 = dttaskinfo.Rows[0]["trayno"].ToString();
                                        bool flag1 = kep.TrayLoad(trayno1, stageloc);
                                        if (flag1 == true)
                                        {
                                            richtbxmsg.AppendText("已解除故障，销钉已升起，即将开始充电\r\n");
                                            Log.SystemError.Add("已解除故障，销钉已升起，即将开始充电");

                                            //将架台,托盘信息存储到数据库中
                                            UpdateStageTrayInfo(stageloc, trayno1);

                                        }
                                        else
                                        {
                                            while (flag1 == false)
                                            {
                                                flag1 = kep.TrayLoad(trayno1, stageloc);
                                            }

                                        }
                                    }
                                    else
                                    {
                                        //Log.WriteLog(LogFile.Trace, "根据架台位置查找托盘编号回复ETL失败，任务里没有架台对应的托盘信息");
                                        Log.SystemError.Add("根据架台号：" + stageloc + "查找托盘编号回复ETL失败，当前任务里没有架台对应的托盘信息");
                                    }


                                }
                                else
                                {

                                }


                                WriteRightValue(93, 1, 1);

                                if (ReadRightValue("593", 1, "0000") == "0000")
                                {
                                    WriteRightValue(93, 1, 0);

                                    hadInInventory = true;
                                    ShowStageTrayInfo(stageloc1, trayno1);

                                }


                            }




                        }



                    }

                    Thread.Sleep(200);
                }

                ldstatus = ReadRightValue("506", 1, "notnull");

                if (ldstatus == "0002")
                {

                    tbxeqsts.Text = "LD运行开始";
                    tbxeqsts.BackColor = Color.SpringGreen;
                }
                else if (ldstatus == "0003")
                {

                    tbxeqsts.Text = "LD到达 装载开始";
                    tbxeqsts.BackColor = Color.SpringGreen;
                }
                else if (ldstatus == "0004")
                {

                    tbxeqsts.Text = "LD装载下降运行开始";
                    tbxeqsts.BackColor = Color.SpringGreen;
                }
                else if (ldstatus == "0005")
                {
                    tbxeqsts.Text = "LD到达 装载下降开始";
                    tbxeqsts.BackColor = Color.SpringGreen;
                }
                //这的延迟很有必要！否则会多次重复读取
                Thread.Sleep(200);


            }

            WriteRightValue(11, 1, 1);
            if (ReadRightValue("511", 1, "0000") == "0000")
            {
                WriteRightValue(11, 1, 0);
            }

            if (tol != "009")
            {
                kep.SendTrayInfo(tox.PadLeft(3, '0') + tol.PadLeft(3, '0') + toc.PadLeft(3, '0'), "","");
            }

            tbxeqsts.Text = "已完成入库";
            tbxeqsts.BackColor = Color.SpringGreen;


            string endcode = ReadRightValue("568", 1, "notnull");
            short endtype = 1;

            if (endcode == "0001")
            {
                endtype = 0;


            }
            else if (endcode == "0002")
            {

                tbxeqsts.Text = "堆垛机异常结束";
                tbxeqsts.BackColor = Color.SpringGreen;
            }

            else if (endcode == "0003")
            {

                tbxeqsts.Text = "堆垛机运行未结束(无装载)";
                tbxeqsts.BackColor = Color.SpringGreen;
            }

            else if (endcode == "0004")
            {

                tbxeqsts.Text = "堆垛机运行未结束(有装载)";
                tbxeqsts.BackColor = Color.SpringGreen;
            }
            

            //即使手动也要生成任务
            string traytype = TrayNo.Substring(TrayNo.Length - 3, 3);
            string recipeid = GetRecipeID(traytype);
            if (string.IsNullOrEmpty(recipeid))
            {
                richtbxmsg.AppendText("请设置正确的托盘类型对应的配方号\r\n");
            }

            short actionid = 120;   //待定
            short priority = 1;
            string usr = "m001";
            bool insertflag = false;

            //先生成出库任务
            try
            {

                task.InsertTask(TrayNo, recipeid, actionid, ActionType, fromlocation, fromx, froml, fromc, tolocation, tox, tol, toc, priority, null, "m", usr, DateTime.Now, null, null, null, 1);
                richtbxmsg.AppendText(TrayNo + "生成出库任务成功!\r\n");
                insertflag = true;

            }
            catch (Exception)
            {
                richtbxmsg.AppendText("保存任务失败,可能是由于格式不正确导致的\r\n");
                while (insertflag == false)
                {
                    try
                    {
                        task.InsertTask(TrayNo, recipeid, actionid, ActionType, fromlocation, fromx, froml, fromc, tolocation, tox, tol, toc, priority, null, "m", usr, DateTime.Now, null, null, null, 1);
                        insertflag = true;
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            //获取刚创建的任务的keyid
            DataTable dttask = task.GetTaskinfoByTrayNo(TrayNo);
            if (dttask.Rows.Count > 0)
            {
                int keyid = int.Parse(dttask.Rows[0]["keyid"].ToString());
                try
                {
                    inserhttask.Insertht_LDTaskList(keyid, short.Parse(endcode), endtype, "a001", DateTime.Now);
                }
                catch (Exception)
                {
                    //Log.WriteLog(LogFile.SystemError,TrayNo+"将任务存入历史任务表失败");
                    Log.SystemError.Add(TrayNo + "将任务存入历史任务表失败");
                }
            }
        }



        private void button14_Click(object sender, EventArgs e)
        {
              
            string value = ReadRightValue5(tbxvalue.Text,1,"notnull"); 
            tbxvalue.Text = value;
        }

       
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            receivethread.Abort();
            receivethread.Interrupt();
            PackPickthread.Abort();//分包初解析线程
            PackPickthread.Interrupt();
            Application.ExitThread();
            
            
        }


        public bool CheckStageIsAvalivale(string stagelocation)
        {
            if (StageStatus.Count > 0)
            {
                for (int i = 0; i < StageStatus.Count; i++)
                {
                    if (StageStatus[i].Stagelocation == "stagelocation")
                    {
                        if (StageStatus[i].Workmode == "1" && StageStatus[i].Currentst == "1" && StageStatus[i].Chargest == "08")
                        {
                            return true;
                        }

                    }
                }
            }
            

            return false;
        }


       
        private void 创建任务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
            form2.Show();
        }

        private void bgCreateTask_DoWork(object sender, DoWorkEventArgs e)
        {
            tbl_stageTrayInfoTableAdapter stagetray = new tbl_stageTrayInfoTableAdapter();
            tbl_LDTaskListTableAdapter task = new tbl_LDTaskListTableAdapter();
            string fromx="";
            string froml="";
            string fromc="";
            string tox="";
            string tol="";
            string toc="";

            string trayno = "";
            bool hadReservation = false;
            while(true)
            {
                
                //从寄存器中获取托盘号
                string rec1510=ReadRightValue2("1510",1,"notnull");
                if (rec1510=="0001")
                {
                    string rec1521 = ReadRightValue2("1521", 1, "notnull");
                    if (rec1521 == "0001")
                    {

                    }
                    else
                    {
                        continue;
                    }
                    kep.SynStageStatus();
                    string rec1530=ReadTrayNo("1530",10,"notnull");
                
                    trayno = rec1530.Substring(0,11);
                    lb91tray.Text = trayno;
                    richtbxmsg.AppendText(DateTime.Now + " 搬入口感知到托盘，托盘号为:" + trayno + "\r\n");

                    //判断当前托盘是否在别的架台充放电
                    int traycount = int.Parse(stagetray.GetTrayNoCountByTrayNo(trayno).ToString());
                    if (traycount > 0)
                    {
                        richtbxmsg.AppendText(DateTime.Now + " 当前搬入的托盘已经在其他架台充放电,创建搬入任务失败！\r\n");
                        continue;
                    }

                    //判断当前托盘已经在未完成的搬入任务里。
                    int taskcount = int.Parse(task.GetTaskCountByTrayNoAndSts(trayno).ToString());
                    if (taskcount > 0)
                    {
                        richtbxmsg.AppendText(DateTime.Now+" 当前搬入的托盘已经在等待搬入任务中,创建搬入任务失败！\r\n");
                        continue;
                    }




                    //判断是否是实验电池，或者41<=电池日期 <=71
                    string receipe = meddal.GetRecipeIDByTrayId(trayno);

                    if (string.IsNullOrEmpty(receipe))
                    {
                        richtbxmsg.AppendText(DateTime.Now+" "+trayno + "托盘为非正常工艺电池或对应电源工艺不存在，创建搬入任务失败!\r\n");
                        continue;
                    }


                    WriteRightValue2(1010,1,1);
                    string receive1510 = ReadRightValue2("1510",1,"0000");
                    if (receive1510 == "0000")
                    {
                        WriteRightValue2(1010, 1, 0);

                        if (HandMode == false)
                        {
                            string stagelocation = GetStageInfoFromDB(trayno);
                            while (string.IsNullOrEmpty(stagelocation))
                            {
                                //kep.SynStageStatus();
                                richtbxmsg.AppendText("无可用架台，持续等待中\r\n");
                                stagelocation = GetStageInfoFromDB(trayno);
                                Thread.Sleep(5000);
                            }
                            if (trayno == "")
                            {
                                Log.SystemError.Add("入线托盘号为空");
                            }
                            //判断是否已经预约
                            if (hadReservation == false)
                            {
                                bool reserveflag = kep.StageReservation(stagelocation);
                                while (!reserveflag)
                                {
                                    richtbxmsg.AppendText(DateTime.Now+"预约架台" + stagelocation + "失败,正在尝试再次预约\r\n");
                                    Thread.Sleep(1000);
                                    reserveflag = kep.StageReservation(stagelocation);
                                }
                                richtbxmsg.AppendText(DateTime.Now + "预约" + stagelocation + "架台成功" + "\r\n");
                                hadReservation = true;

                            }

                            //生成任务需要先预约架台。

                            string traytype = trayno.Substring(trayno.Length - 3, 3);
                            //string recipeid = GetRecipeID(traytype);
                            if (string.IsNullOrEmpty(receipe))
                            {
                                richtbxmsg.AppendText(DateTime.Now + "请设置正确的托盘类型对应的配方号\r\n");

                                continue;
                            }

                            short actionid = 120;   //待定
                            short actiontype = 4;
                            short priority = 10;

                            string usr = "a001";
                            string fromlocation = "001009001";
                            fromx = fromlocation.Substring(0, 3);
                            froml = fromlocation.Substring(3, 3);
                            fromc = fromlocation.Substring(6, 3);
                            string tolocation = stagelocation;

                            tox = tolocation.Substring(0, 3);
                            tol = tolocation.Substring(3, 3);
                            toc = tolocation.Substring(6, 3);

                            try
                            {

                                task.InsertTask(trayno, receipe, actionid, actiontype, fromlocation, fromx, froml, fromc, stagelocation, tox, tol, toc, priority, null, "a", usr, DateTime.Now, null, null, null, 0);
                                //保存成功任务后lock架台
                                //stageinfo.UpdateLockStage(tolocation);
                                richtbxmsg.AppendText(trayno + "生成任务成功!\r\n");
                                trayno = "";
                                hadReservation = false;
                            }
                            catch (Exception)
                            {
                                richtbxmsg.AppendText("保存任务失败,可能是由于格式不正确导致的\r\n");
                            }
                        }   //开始手动模式
                        else
                        {
                           
                        }
                        
                    }
                }
                else
                {

                }
                
                


            }
        }


        //获取托盘信息
        public string ReadTrayNo(string eqadr, int eqno, string expectvalue)
        {
            int ngcount = 1;
            string recvalue = "";

            if (expectvalue != "notnull")
            {
                while (ngcount <= 3 && recvalue != expectvalue)
                {
                    if (st2.Connected() == false)
                    {
                        richtbxmsg.Text = "网络连接断开\r\n";
                         
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st2.Connected() == false)
                        {
                            ReConnect2();
                        }

                    }
                    else if (st2.Connected() == true)
                    {
                        bool rdflag = st2.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }

                        Thread.Sleep(200);
                        recvalue = st2.receiveTrayNo(eqno, "r");
                        ngcount++;

                    }


                }
            }
            else
            {
                while (ngcount <= 3 && recvalue == "")
                {
                    if (st2.Connected() == false)
                    {
                        richtbxmsg.Text = "网络连接断开\r\n";
                         
                        //WriteLogTxt(DateTime.Now + " " + "网络连接断开");
                        while (st2.Connected() == false)
                        {
                            ReConnect();
                        }
                    }
                    else if (st2.Connected())
                    {
                        bool rdflag = st2.sendRddata(eqadr, eqno);
                        if (!rdflag)
                        {
                            //WriteLogTxt(DateTime.Now + "  读取" + eqadr + " 寄存器失败");
                        }
                        Thread.Sleep(200);
                        recvalue = st2.receiveTrayNo(eqno, "r");
                        ngcount++;
                    }

                }
            }

            Thread.Sleep(200);
            return recvalue;

        }



        //获取数据库里的架台信息
        public string  GetStageInfoFromDB(string trayno)
        {
            tbl_stageinfoTableAdapter stageinfo = new tbl_stageinfoTableAdapter();
            string traytype = trayno.Substring(trayno.Length - 3, 3);
            DataTable dbss = new DataTable();
            if (traytype == "C19")
            {

            }
            else if (traytype == "C12" || traytype == "C15")
            { 
                traytype = "C15";
            }
            try
            {
                
                dbss = stageinfo.GetStageStatus(traytype);
            }
            catch (Exception ex )
            {

                Log.SystemError.Add("根据托盘类型查询架台失败"+ex.ToString());
            }
            //while (dbss.Rows.Count <= 0)
            //{
            //    try
            //    {

            //        dbss = stageinfo.GetStageStatus(traytype);
            //    }
            //    catch (Exception ex)
            //    {

            //        Log.SystemError.Add("根据托盘类型查询架台失败" + ex.ToString());
            //    }
            //}
            //判断架台是否空闲或架台是否有任务!
            if (dbss.Rows.Count > 0)
            {
                //for (int i = 0; i < dbss.Rows.Count; i++)
                //{
                //    //查询对应类型的架台是否已经被预约，如果被预约的话则不等待。修改人：suozhengwei 2017-4-13 01:37:21
                    string stagelocation = dbss.Rows[0]["stagelocation"].ToString();
                //    int IsFree = int.Parse(stageinfo.SelectFreeStageinfoByStageLocation(stagelocation).ToString());
                //    if (IsFree > 0)
                //    {
                        return stagelocation;
                //    }

                //}
            }

            return "";
        }

        public string GetRecipeID(string traytype)
        {
            tb_RecipeInfoTableAdapter recipeinfo = new tb_RecipeInfoTableAdapter();
            DataTable dtrecipeinfo = new DataTable();
            dtrecipeinfo = recipeinfo.GetRecipeInfoByRecipeid(traytype);
            if (dtrecipeinfo.Rows.Count > 0)
            {

                return dtrecipeinfo.Rows[0]["recipeid"].ToString();
            }else
                {
                    ////richtbxmsg.AppendText("请设置正确的托盘类型\r\n");
                   
                    return "";
                }
           
            
        }

        private void bgQueryStageInfo_DoWork(object sender, DoWorkEventArgs e)
        {
            StageStatus = kep.SynStageStatus();
        }

        private void timerUpdateStageInfo_Tick(object sender, EventArgs e)
        {
            bgQueryStageInfo.RunWorkerAsync();
        }

        private void 查询当前任务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormCurrentTask currtask = new FormCurrentTask();
            currtask.Show();
        }

        private void button2_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {

        }

        private void bginitial_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {

                //接收线程
                receivethread = new Thread(receiveByte);
                receivethread.Start();
                //分包解析线程
                PackPickthread = new Thread(BufferPackPick);
                PackPickthread.Start();
                packPick = new CDPackPick();
                kep = new KapjinEqProtocol(iSocket);
                //bgwAliveSignal.RunWorkerAsync();

                //timerSynTime.Enabled = true;
                //bgQueryStageInfo.RunWorkerAsync();
                //bgOutAndInInventory.RunWorkerAsync();
                //bgReplayECS.RunWorkerAsync();
                //bgCreateTask.RunWorkerAsync();

            }
            catch (Exception ex)
            {
                //richtxtClient.Text += "连接服务器失败！\n" + ex;
                Exceptionlog.InsertException(ex);

                return;
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
           
            if (kep.SynStageStatus().Count > 0)
            {

                MessageBox.Show("与ECS连接正常");
              
            }
            else
            {
                MessageBox.Show("与ECS连接异常");
            }
        }

        private void button2_Click_1(object sender, EventArgs e)
        {

            //string receipe = meddal.GetRecipeIDByTrayId("H027760-C19");
            string stagelocation = GetStageInfoFromDB("H027760 - C15");
            //DataTable dtCellData = frdata.GetCellDataByTrayCellNoEndTime("HQL07C15FHSB011157", "H004404-C12", DateTime.Parse("2016-12-28 14:59:20.000"));
            //DataRow[] dr = dtCellData.Select("stepno=" + 1);


        }

        private void bgFreshStageSts_DoWork(object sender, DoWorkEventArgs e)
        {
            tbl_stageTrayInfoTableAdapter stagetray = new tbl_stageTrayInfoTableAdapter();
            tbl_stageinfoTableAdapter stageinfo = new tbl_stageinfoTableAdapter();
            DataTable dtstagests = new DataTable();
                dtstagests = stageinfo.GetCurrentStatus();

                DataTable dtstagetray = stagetray.GetData();
                string stagelocation = "";
                string currentst = "";
                string workmode = "";
                string chargest = "";
                string stagetrayloc = "";
                string stagetrayno = "";
                for (int i = 0; i < dtstagests.Rows.Count; i++)
                {
                    workmode = dtstagests.Rows[i]["workmode"].ToString();
                    stagelocation = dtstagests.Rows[i]["stagelocation"].ToString();
                    currentst = dtstagests.Rows[i]["currentst"].ToString();
                    chargest = dtstagests.Rows[i]["chargest"].ToString();
                    if (workmode == "1" && currentst == "1" && chargest == "08")
                    {
                        UpdateStageStatus(stagelocation, "可用");

                    }
                    else if (currentst == "4")
                    {
                        UpdateStageStatus(stagelocation, "已预约");
                    }
                    else
                    {
                        UpdateStageStatus(stagelocation, "不可用");
                    }
                }

                for (int i = 0; i < dtstagetray.Rows.Count; i++)
                {
                    stagetrayloc = dtstagetray.Rows[i]["stagelocation"].ToString();
                    stagetrayno = dtstagetray.Rows[i]["trayno"].ToString();
                    ShowStageTrayInfo(stagetrayloc, stagetrayno);
                }


                
            
            
        }


        public void UpdateStageStatus(string stagelocation, string stagests)
        {
            if (stagelocation == "001001001" )
            {
                if (stagests == "可用")
                {
                    bt11c.BackColor = Color.SpringGreen;
                    lb11sts.BackColor = Color.SpringGreen;
                    lb11tray.BackColor = Color.SpringGreen;
                        
                }
                else if (stagests == "已预约")
                {
                    bt11c.BackColor = Color.Pink;
                    lb11sts.BackColor = Color.Pink;
                    lb11tray.BackColor = Color.Pink;
                }
                else
                {
                    bt11c.BackColor = Color.SkyBlue;
                    lb11sts.BackColor = Color.SkyBlue;
                    lb11tray.BackColor = Color.SkyBlue;
                }
                
            }
            if (stagelocation == "001001002" )
            {
                if (stagests == "可用")
                {
                    bt12c.BackColor = Color.SpringGreen;
                    lb12sts.BackColor = Color.SpringGreen;
                    lb12tray.BackColor = Color.SpringGreen;
                }
                else if (stagests == "已预约")
                {
                    bt12c.BackColor = Color.Pink;
                    lb12sts.BackColor = Color.Pink;
                    lb12tray.BackColor = Color.Pink;
                }
                else
                {
                    bt12c.BackColor = Color.SkyBlue;
                    lb12sts.BackColor = Color.SkyBlue;
                    lb12tray.BackColor = Color.SkyBlue;
                }
            }
            if (stagelocation == "001001003" )
            {
                if (stagests == "可用")
                {
                    bt13c.BackColor = Color.SpringGreen;
                    lb13sts.BackColor = Color.SpringGreen;
                    lb13tray.BackColor = Color.SpringGreen;
                }
                else if (stagests == "已预约")
                {
                    bt13c.BackColor = Color.Pink;
                    lb13sts.BackColor = Color.Pink;
                    lb13tray.BackColor = Color.Pink;
                }
                else
                {
                    bt13c.BackColor = Color.SkyBlue;
                    lb13sts.BackColor = Color.SkyBlue;
                    lb13tray.BackColor = Color.SkyBlue;
                }
            }
            if (stagelocation == "001002001" )
            {
                if (stagests == "可用")
                {
                    bt21c.BackColor = Color.SpringGreen;
                    lb21sts.BackColor = Color.SpringGreen;
                    lb21tray.BackColor = Color.SpringGreen;
                }
                else if (stagests == "已预约")
                {
                    bt21c.BackColor = Color.Pink;
                    lb21sts.BackColor = Color.Pink;
                    lb21tray.BackColor = Color.Pink;
                }
                else
                {
                    bt21c.BackColor = Color.SkyBlue;
                    lb21sts.BackColor = Color.SkyBlue;
                    lb21tray.BackColor = Color.SkyBlue;
                }
            }
            if (stagelocation == "001002002" )
            {
                if (stagests == "可用")
                {
                    bt22c.BackColor = Color.SpringGreen;
                    lb22sts.BackColor = Color.SpringGreen;
                    lb22tray.BackColor = Color.SpringGreen;
                }
                else if (stagests == "已预约")
                {
                    bt22c.BackColor = Color.Pink;
                    lb22sts.BackColor = Color.Pink;
                    lb22tray.BackColor = Color.Pink;
                }
                else
                {
                    bt22c.BackColor = Color.SkyBlue;
                    lb22sts.BackColor = Color.SkyBlue;
                    lb22tray.BackColor = Color.SkyBlue;
                }
            }
            if (stagelocation == "001002003" )
            {
                if (stagests == "可用")
                {
                    bt23c.BackColor = Color.SpringGreen;
                    lb23sts.BackColor = Color.SpringGreen;
                    lb23tray.BackColor = Color.SpringGreen;
                }
                else if (stagests == "已预约")
                {
                    bt23c.BackColor = Color.Pink;
                    lb23sts.BackColor = Color.Pink;
                    lb23tray.BackColor = Color.Pink;
                }
                else
                {
                    bt23c.BackColor = Color.SkyBlue;
                    lb23sts.BackColor = Color.SkyBlue;
                    lb23tray.BackColor = Color.SkyBlue;
                }
            }
            if (stagelocation == "001003001")
            {
                if (stagests == "可用")
                {
                    bt31c.BackColor = Color.SpringGreen;
                    lb31sts.BackColor = Color.SpringGreen;
                    lb31tray.BackColor = Color.SpringGreen;
                }
                else if (stagests == "已预约")
                {
                    bt31c.BackColor = Color.Pink;
                    lb31sts.BackColor = Color.Pink;
                    lb31tray.BackColor = Color.Pink;
                }
                else
                {
                    bt31c.BackColor = Color.SkyBlue;
                    lb31sts.BackColor = Color.SkyBlue;
                    lb31tray.BackColor = Color.SkyBlue;
                }
            }
            if (stagelocation == "001003002" )
            {
                if (stagests == "可用")
                {
                    bt32c.BackColor = Color.SpringGreen;
                    lb32sts.BackColor = Color.SpringGreen;
                    lb32tray.BackColor = Color.SpringGreen;
                }
                else if (stagests == "已预约")
                {
                    bt32c.BackColor = Color.Pink;
                    lb32sts.BackColor = Color.Pink;
                    lb32tray.BackColor = Color.Pink;
                }
                else
                {
                    bt32c.BackColor = Color.SkyBlue;
                    lb32sts.BackColor = Color.SkyBlue;
                    lb32tray.BackColor = Color.SkyBlue;
                }
            }
            if (stagelocation == "001003003" )
            {
                if (stagests == "可用")
                {
                    bt33c.BackColor = Color.SpringGreen;
                    lb33sts.BackColor = Color.SpringGreen;
                    lb33tray.BackColor = Color.SpringGreen;
                }
                else if (stagests == "已预约")
                {
                    bt33c.BackColor = Color.Pink;
                    lb33sts.BackColor = Color.Pink;
                    lb33tray.BackColor = Color.Pink;
                }
                else
                {
                    bt33c.BackColor = Color.SkyBlue;
                    lb33sts.BackColor = Color.SkyBlue;
                    lb33tray.BackColor = Color.SkyBlue;
                }
            }
            if (stagelocation == "001004001" )
            {
                if (stagests == "可用")
                {
                    bt41c.BackColor = Color.SpringGreen;
                    lb41sts.BackColor = Color.SpringGreen;
                    lb41tray.BackColor = Color.SpringGreen;
                }
                else if (stagests == "已预约")
                {
                    bt41c.BackColor = Color.Pink;
                    lb41sts.BackColor = Color.Pink;
                    lb41tray.BackColor = Color.Pink;
                }
                else
                {
                    bt41c.BackColor = Color.SkyBlue;
                    lb41sts.BackColor = Color.SkyBlue;
                    lb41tray.BackColor = Color.SkyBlue;
                }
            }
            if (stagelocation == "001004002" )
            {
                if (stagests == "可用")
                {
                    bt42c.BackColor = Color.SpringGreen;
                    lb42sts.BackColor = Color.SpringGreen;
                    lb42tray.BackColor = Color.SpringGreen;
                }
                else if (stagests == "已预约")
                {
                    bt42c.BackColor = Color.Pink;
                    lb42sts.BackColor = Color.Pink;
                    lb42tray.BackColor = Color.Pink;
                }
                else
                {
                    bt42c.BackColor = Color.SkyBlue;
                    lb42sts.BackColor = Color.SkyBlue;
                    lb42tray.BackColor = Color.SkyBlue;
                }
            }
            if (stagelocation == "001004003" )
            {
                if (stagests == "可用")
                {
                    bt43c.BackColor = Color.SpringGreen;
                    lb43sts.BackColor = Color.SpringGreen;
                    lb43tray.BackColor = Color.SpringGreen;
                }
                else if (stagests == "已预约")
                {
                    bt43c.BackColor = Color.Pink;
                    lb43sts.BackColor = Color.Pink;
                    lb43tray.BackColor = Color.Pink;
                }
                else
                {
                    bt43c.BackColor = Color.SkyBlue;
                    lb43sts.BackColor = Color.SkyBlue;
                    lb43tray.BackColor = Color.SkyBlue;
                }
            }
            if (stagelocation == "001005001" )
            {
                if (stagests == "可用")
                {
                    bt51c.BackColor = Color.SpringGreen;
                    lb51sts.BackColor = Color.SpringGreen;
                    lb51tray.BackColor = Color.SpringGreen;
                }
                else if (stagests == "已预约")
                {
                    bt51c.BackColor = Color.Pink;
                    lb51sts.BackColor = Color.Pink;
                    lb51tray.BackColor = Color.Pink;
                }
                else
                {
                    bt51c.BackColor = Color.SkyBlue;
                    lb51sts.BackColor = Color.SkyBlue;
                    lb51tray.BackColor = Color.SkyBlue;
                }
            }
            if (stagelocation == "001005002" )
            {
                if (stagests == "可用")
                {
                    bt52c.BackColor = Color.SpringGreen;
                    lb52sts.BackColor = Color.SpringGreen;
                    lb52tray.BackColor = Color.SpringGreen;
                }
                else if (stagests == "已预约")
                {
                    bt52c.BackColor = Color.Pink;
                    lb52sts.BackColor = Color.Pink;
                    lb52tray.BackColor = Color.Pink;
                }
                else
                {
                    bt52c.BackColor = Color.SkyBlue;
                    lb52sts.BackColor = Color.SkyBlue;
                    lb52tray.BackColor = Color.SkyBlue;
                }
            }
            if (stagelocation == "001005003" )
            {
                if (stagests == "可用")
                {
                    bt53c.BackColor = Color.SpringGreen;
                    lb53sts.BackColor = Color.SpringGreen;
                    lb53tray.BackColor = Color.SpringGreen;
                }
                else if (stagests == "已预约")
                {
                    bt53c.BackColor = Color.Pink;
                    lb53sts.BackColor = Color.Pink;
                    lb53tray.BackColor = Color.Pink;
                }
                else
                {
                    bt53c.BackColor = Color.SkyBlue;
                    lb53sts.BackColor = Color.SkyBlue;
                    lb53tray.BackColor = Color.SkyBlue;
                }
            }
            if (stagelocation == "001006001" )
            {
                if (stagests == "可用")
                {
                    bt61c.BackColor = Color.SpringGreen;
                    lb61sts.BackColor = Color.SpringGreen;
                    lb61tray.BackColor = Color.SpringGreen;
                }
                else if (stagests == "已预约")
                {
                    bt61c.BackColor = Color.Pink;
                    lb61sts.BackColor = Color.Pink;
                    lb61tray.BackColor = Color.Pink;
                }
                else
                {
                    bt61c.BackColor = Color.SkyBlue;
                    lb61sts.BackColor = Color.SkyBlue;
                    lb61tray.BackColor = Color.SkyBlue;
                }
            }
            if (stagelocation == "001006002" )
            {
                if (stagests == "可用")
                {
                    bt62c.BackColor = Color.SpringGreen;
                    lb62sts.BackColor = Color.SpringGreen;
                    lb62tray.BackColor = Color.SpringGreen;
                }
                else if (stagests == "已预约")
                {
                    bt62c.BackColor = Color.Pink;
                    lb62sts.BackColor = Color.Pink;
                    lb62tray.BackColor = Color.Pink;
                }
                else
                {
                    bt62c.BackColor = Color.SkyBlue;
                    lb62sts.BackColor = Color.SkyBlue;
                    lb62tray.BackColor = Color.SkyBlue;
                }
            }
            if (stagelocation == "001006003" )
            {
                if (stagests == "可用")
                {
                    bt63c.BackColor = Color.SpringGreen;
                    lb63sts.BackColor = Color.SpringGreen;
                    lb63tray.BackColor = Color.SpringGreen;
                }
                else if (stagests == "已预约")
                {
                    bt63c.BackColor = Color.Pink;
                    lb63sts.BackColor = Color.Pink;
                    lb63tray.BackColor = Color.Pink;
                }
                else
                {
                    bt63c.BackColor = Color.SkyBlue;
                    lb63sts.BackColor = Color.SkyBlue;
                    lb63tray.BackColor = Color.SkyBlue;
                }
            }
            
        }
        //将架台信息同步到数据库
        public void UpdateStageTrayInfo(string stagelocation, string trayno)
        {
            tbl_stageTrayInfoTableAdapter stagetray = new tbl_stageTrayInfoTableAdapter();
            int allowcout=3;
            int ngcount=0;
            int stagetrayno=0;
            try
            {
                stagetrayno = int.Parse(stagetray.GetStageTrayNo(stagelocation).ToString());
            }
            catch (Exception ex)
            {

                Log.SystemError.Add(ex.ToString());
            }
            
            string receipeid = "";
            if (string.IsNullOrEmpty(trayno))
            {
                receipeid = "";
            }
            else
            {
                receipeid = meddal.GetRecipeIDByTrayId(trayno);
            }
             
             bool dbflag = false;
                if (stagetrayno > 0)
                {
                    try
                    {
                        stagetray.UpdateTrayNoByLocation(trayno, stagelocation);
                        ngcount++;
                        dbflag = true;
                        ngcount = 0;
                    }
                    catch (Exception ex)
                    {

                        Log.SystemError.Add("将架台托盘信息存如数据库时发送错误。"+ex.ToString());
                        richtbxmsg.AppendText("将架台托盘信息存储数据库时发生错误。\r\n");
                        while (dbflag == false && ngcount<allowcout)
                        {
                            try
                            {
                                stagetray.UpdateTrayNoByLocation(trayno, stagelocation);
                                 ngcount++;
                                dbflag = true;
                                ngcount = 0;
                            }
                            catch (Exception ex1)
                            {
                                ngcount++;
                                Log.SystemError.Add("将架台托盘信息存如数据库时发送错误。" + ex1.ToString());
                                richtbxmsg.AppendText("将架台托盘信息存储数据库时发生错误。\r\n");
                            }

                        }
                    }
                    

                }
                else
                {
                    
                    try
                    {
                        stagetray.InsertStageTrayInfo(stagelocation, trayno, receipeid, null, null);
                        ngcount++;
                        dbflag = true;
                        ngcount = 0;
                    }
                    catch (Exception ex)
                    {

                        Log.SystemError.Add("将架台托盘信息存如数据库时发送错误。" + ex.ToString());
                        richtbxmsg.AppendText("将架台托盘信息存储数据库时发生错误。\r\n");
                        while (dbflag == false && ngcount < allowcout)
                        {
                            try
                            {
                                stagetray.InsertStageTrayInfo(stagelocation, trayno, receipeid, null, null);
                                ngcount++;
                                dbflag = true;
                                ngcount = 0;
                                
                            }
                            catch (Exception ex1)
                            {
                                ngcount++;
                                Log.SystemError.Add("将架台托盘信息存储数据库时发生错误。" + ex1.ToString());
                            }

                        }
                    }
                }
            
        }

        

        public void ShowStageTrayInfo(string stagelocation, string trayno)
        {
          
            if (stagelocation == "001001001" )
            {
                lb11tray.Text = trayno;
            }
            if (stagelocation == "001001002")
            {
                lb12tray.Text = trayno;
            }
            if (stagelocation == "001001003" )
            {
                lb13tray.Text = trayno;
            }
            if (stagelocation == "001002001")
            {
                lb21tray.Text = trayno;
            }
            if (stagelocation == "001002002")
            {
                lb22tray.Text = trayno;
            }
            if (stagelocation == "001002003")
            {
                lb23tray.Text = trayno;
            }
            if (stagelocation == "001003001")
            {
                lb31tray.Text = trayno;
            }
            if (stagelocation == "001003002")
            {
                lb32tray.Text = trayno;
            }
            if (stagelocation == "001003003")
            {
                lb33tray.Text = trayno;
            }
            if (stagelocation == "001004001")
            {
                lb41tray.Text = trayno;
            }
            if (stagelocation == "001004002")
            {
                lb42tray.Text = trayno;
            }
            if (stagelocation == "001004003")
            {
                lb43tray.Text = trayno;
            }
            if (stagelocation == "001005001")
            {
                lb51tray.Text = trayno;
            }
            if (stagelocation == "001005002")
            {
                lb52tray.Text = trayno;
            }
            if (stagelocation == "001005003")
            {
                lb53tray.Text = trayno;
            }
            if (stagelocation == "001006001")
            {
                lb61tray.Text = trayno;
            }
            if (stagelocation == "001006002")
            {
                lb62tray.Text = trayno;
            }
            if (stagelocation == "001006003")
            {
                lb63tray.Text = trayno;
            }
        }



        public void ClearStageTrayInfo(string stagelocation)
        {

            if (stagelocation == "001001001")
            {
                lb11tray.Text = "";
            }
            if (stagelocation == "001001002")
            {
                lb12tray.Text = "";
            }
            if (stagelocation == "001001003")
            {
                lb13tray.Text = "";
            }
            if (stagelocation == "001002001")
            {
                lb21tray.Text = "";
            }
            if (stagelocation == "001002002")
            {
                lb22tray.Text = "";
            }
            if (stagelocation == "001002003")
            {
                lb23tray.Text = "";
            }
            if (stagelocation == "001003001")
            {
                lb31tray.Text = "";
            }
            if (stagelocation == "001003002")
            {
                lb32tray.Text = "";
            }
            if (stagelocation == "001003003")
            {
                lb33tray.Text = "";
            }
            if (stagelocation == "001004001")
            {
                lb41tray.Text = "";
            }
            if (stagelocation == "001004002")
            {
                lb42tray.Text = "";
            }
            if (stagelocation == "001004003")
            {
                lb43tray.Text = "";
            }
            if (stagelocation == "001005001")
            {
                lb51tray.Text = "";
            }
            if (stagelocation == "001005002")
            {
                lb52tray.Text = "";
            }
            if (stagelocation == "001005003")
            {
                lb53tray.Text = "";
            }
            if (stagelocation == "001006001")
            {
                lb61tray.Text = "";
            }
            if (stagelocation == "001006002")
            {
                lb62tray.Text = "";
            }
            if (stagelocation == "001006003")
            {
                lb63tray.Text = "";
            }
        }

        public void ClearStageTrayInfoAndDBInfo(string stagelocation)
        {
            tbl_stageTrayInfoTableAdapter stagetray = new tbl_stageTrayInfoTableAdapter();
            if (stagelocation == "001001001")
            {
                lb11tray.Text = "";
                stagetray.UpdateTrayNoByLocation("", stagelocation);
            }
            if (stagelocation == "001001002")
            {
                lb12tray.Text = "";
                stagetray.UpdateTrayNoByLocation("", stagelocation);
            }
            if (stagelocation == "001001003")
            {
                lb13tray.Text = "";
                stagetray.UpdateTrayNoByLocation("", stagelocation);
            }
            if (stagelocation == "001002001")
            {
                lb21tray.Text = "";
                stagetray.UpdateTrayNoByLocation("", stagelocation);
            }
            if (stagelocation == "001002002")
            {
                lb22tray.Text = "";
                stagetray.UpdateTrayNoByLocation("", stagelocation);
            }
            if (stagelocation == "001002003")
            {
                lb23tray.Text = "";
                stagetray.UpdateTrayNoByLocation("", stagelocation);
            }
            if (stagelocation == "001003001")
            {
                lb31tray.Text = "";
                stagetray.UpdateTrayNoByLocation("", stagelocation);
            }
            if (stagelocation == "001003002")
            {
                lb32tray.Text = "";
                stagetray.UpdateTrayNoByLocation("", stagelocation);
            }
            if (stagelocation == "001003003")
            {
                lb33tray.Text = "";
                stagetray.UpdateTrayNoByLocation("", stagelocation);
            }
            if (stagelocation == "001004001")
            {
                lb41tray.Text = "";
                stagetray.UpdateTrayNoByLocation("", stagelocation);
            }
            if (stagelocation == "001004002")
            {
                lb42tray.Text = "";
                stagetray.UpdateTrayNoByLocation("", stagelocation);
            }
            if (stagelocation == "001004003")
            {
                lb43tray.Text = "";
                stagetray.UpdateTrayNoByLocation("", stagelocation);
            }
            if (stagelocation == "001005001")
            {
                lb51tray.Text = "";
                stagetray.UpdateTrayNoByLocation("", stagelocation);
            }
            if (stagelocation == "001005002")
            {
                lb52tray.Text = "";
                stagetray.UpdateTrayNoByLocation("", stagelocation);
            }
            if (stagelocation == "001005003")
            {
                lb53tray.Text = "";
                stagetray.UpdateTrayNoByLocation("", stagelocation);
            }
            if (stagelocation == "001006001")
            {
                lb61tray.Text = "";
                stagetray.UpdateTrayNoByLocation("", stagelocation);
            }
            if (stagelocation == "001006002")
            {
                lb62tray.Text = "";
                stagetray.UpdateTrayNoByLocation("", stagelocation);
            }
            if (stagelocation == "001006003")
            {
                lb63tray.Text = "";
                stagetray.UpdateTrayNoByLocation("", stagelocation);
            }
        }



        public void UpdateStageTrayInfoNull(string stagelocation,string trayno)
        {
            if (stagelocation=="001001001")
            {
                lb11tray.Text=trayno;
            }
            if (stagelocation=="001001002")
            {
                lb12tray.Text=trayno;
            }
            if (stagelocation=="001001003")
            {
                lb13tray.Text=trayno;
            }
            if (stagelocation=="001002001")
            {
                lb21tray.Text=trayno;
            }
            if (stagelocation=="001002002")
            {
                lb22tray.Text=trayno;
            }
            if (stagelocation=="001002003")
            {
                lb23tray.Text=trayno;
            }
            if (stagelocation=="001003001")
            {
                lb31tray.Text=trayno;
            }
            if (stagelocation=="001003002")
            {
                lb32tray.Text=trayno;
            }
            if (stagelocation=="001003003")
            {
                lb33tray.Text=trayno;
            }
            if (stagelocation=="001004001")
            {
                lb41tray.Text=trayno;
            }
            if (stagelocation=="001004002")
            {
                lb42tray.Text=trayno;
            }
            if (stagelocation=="001004003")
            {
                lb43tray.Text=trayno;
            }
            if (stagelocation=="001005001")
            {
                lb51tray.Text=trayno;
            }
            if (stagelocation=="001005002")
            {
                lb52tray.Text=trayno;
            }
            if (stagelocation=="001005003")
            {
                lb53tray.Text=trayno;
            }
            if (stagelocation=="001006001")
            {
                lb61tray.Text=trayno;
            }
            if (stagelocation=="001006002")
            {
                lb62tray.Text=trayno;
            }
            if (stagelocation=="001006003")
            {
                lb63tray.Text=trayno;
            }
        }


        private void bgWriteLog_DoWork(object sender, DoWorkEventArgs e)
        {

            while (true)
            { 
                while (Log.Trace.Count>0)
                {
                    Log.WriteLog(LogFile.Trace,Log.Trace[0]);
                    if (Log.Trace.Count > 0)
                    {
                        Log.Trace.RemoveAt(0);
                    }
                    
                }
                while (Log.MeasureWarning.Count > 0)
                {
                    Log.WriteLog(LogFile.MeasureWarning, Log.MeasureWarning[0]);
                    if (Log.MeasureWarning.Count > 0)
                    {
                        Log.MeasureWarning.RemoveAt(0);
                    }
                }
                while (Log.MeasureError.Count > 0)
                {
                    Log.WriteLog(LogFile.MeasureError, Log.MeasureError[0]);
                    if (Log.MeasureError.Count > 0)
                    {
                        Log.MeasureError.RemoveAt(0);
                    }
                }
                while (Log.SQL.Count > 0)
                {
                    Log.WriteLog(LogFile.SQL, Log.SQL[0]);
                    if (Log.SQL.Count > 0)
                    {
                        Log.SQL.RemoveAt(0);
                    }
                }
                while (Log.SystemError.Count > 0)
                {
                    Log.WriteLog(LogFile.SystemError, Log.SystemError[0]);
                    if (Log.SystemError.Count > 0)
                    {
                        Log.SystemError.RemoveAt(0);
                    }
                }
                while (Log.ReciveFromECS.Count > 0)
                {
                    Log.WriteLog(LogFile.ReciveFromECS, Log.ReciveFromECS[0]);
                    if (Log.ReciveFromECS.Count > 0)
                    {
                        Log.ReciveFromECS.RemoveAt(0);
                    }
                }
                while (Log.SendToECS.Count > 0)
                {
                    Log.WriteLog(LogFile.SendToECS, Log.SendToECS[0]);
                    if (Log.SendToECS.Count > 0)
                    {
                        Log.SendToECS.RemoveAt(0);
                    }
                }

                Thread.Sleep(1000);
            }
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            if (kep.StageReservation("001005002"))
            {
                MessageBox.Show("架台预约成功");

            }
            
        }

        private void bgReplayForkSts_DoWork(object sender, DoWorkEventArgs e)
        {
            ht_LDTaskListTableAdapter httask = new ht_LDTaskListTableAdapter();
            while (true)
            {
                string fromx = "";
                string froml = "";
                string fromc = "";
                int ngcount = 0;
                

                string rec590 = ReadRightValue3("590", 1, "notnull");
                string rec591 = ReadRightValue3("591", 1, "notnull");
                string rec592 = ReadRightValue3("592", 1, "notnull");
                fromx = rec590.Substring(3, 1);
                froml = rec591.Substring(3, 1);
                fromc = rec592.Substring(3, 1);
               
                WriteRightValue3(90, 1, int.Parse(fromx.PadLeft(4, '0')));
                //Thread.Sleep(200);
                WriteRightValue3(91, 1, int.Parse(froml.PadLeft(4, '0')));
                
                WriteRightValue3(92, 1, int.Parse(fromc.PadLeft(4, '0')));
                // Thread.Sleep(200);
                
                //Thread.Sleep(500);
                string rec593 = ReadRightValue3("593", 1, "0002");
                //Thread.Sleep(200);

                if (rec593 == "0002")
                {
                    fromx = rec590.Substring(3, 1);
                    froml = rec591.Substring(3, 1);
                    fromc = rec592.Substring(3, 1);
                    if (froml != "9")
                    {
                        DataTable dttrayinfo = new DataTable();
                        string stageloc = rec590.Substring(1, 3) + rec591.Substring(1, 3) + rec592.Substring(1, 3);
                        dttrayinfo = httask.GetTrayNoFromHtTask(stageloc);
                        string TrayNo = "";
                        if (dttrayinfo.Rows.Count > 0)
                        {
                            TrayNo = dttrayinfo.Rows[0]["trayno"].ToString();
                        }
                        tbxeqsts.Text = "出库已就位";
                        tbxeqsts.BackColor = Color.SpringGreen;
                        //WUR
                        bool flag = kep.UpLoadingReservation(fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0'));
                        if (flag == false)
                        {
                            richtbxmsg.AppendText("装载托盘完成，ECS销钉下降失败\r\n");
                            Log.SystemError.Add(TrayNo + "ECS出库销钉下降失败\r\n");
                            ngcount++;
                            while (flag == false)
                            {
                                if (ngcount > 3)
                                {
                                    break;
                                }
                                flag = kep.UpLoadingReservation(fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0'));
                                ngcount++;
                            }
                            //更改当前架台的数据库的托盘号为空
                            UpdateStageTrayInfo(fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0'),"");
                            //将当前架台的托盘号显示清空
                            ClearStageTrayInfo(fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0'));
                        }
                        else
                        {

                          
                            Thread.Sleep(600);
                            WriteRightValue3(93, 1, 2);
                            
                            if (ReadRightValue3("593", 1, "0000") == "0000")
                            {
                                WriteRightValue3(93, 1, 0);
                               
                                tbxeqsts.Text = "已完成出库";
                                tbxeqsts.BackColor = Color.SpringGreen;
                                ClearStageTrayInfo(fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0'));
                                //通知ECS Notify tray unloading completion   WTU
                                Thread.Sleep(2000);
                                bool flag1 = kep.TrayUnload(TrayNo.PadRight(20, ' '), fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0'));

                                if (flag1 == false)
                                {
                                    //Log.WriteLog(LogFile.SystemError, "WTU异常");
                                    Log.SystemError.Add("WTU异常");
                                    //richtbxmsg.AppendText = "WTU异常";
                                    richtbxmsg.AppendText("WTU异常\r\n");
                                }
                                else
                                {
                                    //richtbxmsg.AppendText("UpLoading托盘成功");
                                    //更改当前架台的数据库的托盘号为空
                                    UpdateStageTrayInfo(fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0'), "");
                                    //将当前架台的托盘号显示清空
                                    ClearStageTrayInfo(fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0'));
                                }


                            }
                            else
                            {
                                Log.SystemError.Add("W0593未复位");
                                richtbxmsg.AppendText("PLC异常，请复位PLC\r\n");

                            }
                        }
                    }
                    else if (froml == "9"&& fromc=="1")
                    {
                        WriteRightValue4(90, 1, int.Parse(fromx.PadLeft(4, '0')));
                        //Thread.Sleep(200);
                        WriteRightValue4(91, 1, int.Parse(froml.PadLeft(4, '0')));
                        //Thread.Sleep(200);
                        WriteRightValue4(92, 1, int.Parse(fromc.PadLeft(4, '0')));

                        Thread.Sleep(600);
                        string rec152A = ReadRightValue4("152A", 1, "notnull");

                        if (rec152A == "0001" && rec593 == "0002")
                        {
                           
                            tbxeqsts.Text = "出库已就位";
                            tbxeqsts.BackColor = Color.SpringGreen;
                            WriteRightValue4(93, 1, 2);
                           
                            if (ReadRightValue4("593", 1, "0000") == "0000")
                            {
                                WriteRightValue4(93, 1, 0);
                                tbxeqsts.Text = "出库已完成";
                                tbxeqsts.BackColor = Color.SpringGreen;

                            }
                            else
                            {
                                //richtbxmsg.Text = "PLC异常";
                                richtbxmsg.AppendText("PLC异常W0593未复位\r\n");
                                // Log.WriteLog(LogFile.SystemError, TrayNo + " W0593未复位\r\n");
                                Log.SystemError.Add(" W0593未复位");
                            }
                        }
                        else
                        {
                            Log.SystemError.Add("入口销钉下降失败,程序等待中");
                            richtbxmsg.AppendText("入口销钉下降失败,程序等待中\r\n");
                            Thread.Sleep(1000);
                        }
                    
                    }
                }
                else
                {
                    string st1sts = ReadRightValue3("1521", 1, "notnull");
                    if (st1sts == "0001")
                    {
                        bt91c.BackColor = Color.SkyBlue;
                        lb91sts.BackColor = Color.SkyBlue;
                        lb91tray.BackColor = Color.SkyBlue;
                        //lb92tray.Text = "占用";
                    }
                    else
                    {
                        bt91c.BackColor = Color.SpringGreen;
                        lb91sts.BackColor = Color.SpringGreen;
                        lb91tray.BackColor = Color.SpringGreen;
                        //lb92tray.Text = "空";
                    }

                    string checksts = ReadRightValue3("1526", 1, "notnull");
                    if (checksts == "0001")
                    {
                        bt92c.BackColor = Color.SkyBlue;
                        lb92sts.BackColor = Color.SkyBlue;
                        lb92tray.BackColor = Color.SkyBlue;
                        //lb92tray.Text = "占用";
                    }
                    else
                    {
                        bt92c.BackColor = Color.SpringGreen;
                        lb92sts.BackColor = Color.SpringGreen;
                        lb92tray.BackColor = Color.SpringGreen;
                        //lb92tray.Text = "空";
                    }

                    string outsts = ReadRightValue3("1523", 1, "notnull");
                    if (outsts == "0001")
                    {
                        bt93c.BackColor = Color.SkyBlue;
                        lb93sts.BackColor = Color.SkyBlue;
                        lb93tray.BackColor = Color.SkyBlue;
                        //lb93tray.Text = "占用";
                    }
                    else
                    {
                        bt93c.BackColor = Color.SpringGreen;
                        lb93sts.BackColor = Color.SpringGreen;
                        lb93tray.BackColor = Color.SpringGreen;
                        //lb93tray.Text = "空";
                    }

                }
                Thread.Sleep(1000);


            }
        }
        

        private void button3_Click_2(object sender, EventArgs e)
        {
           
            StaticArg.CheckStatus = "open";
            FormClosedCheck cc = new FormClosedCheck();
            cc.ShowDialog();

            if (StaticArg.CheckStatus == "close")
            {
                if (tbxrunmode.Text == "自动中")
                {
                    HandMode = true;
                    tbxrunmode.Text = "手动中";
                    tbxtrayno1.Visible = true;
                    listboxstageloc.Visible = true;
                    btmove.Visible = true;
                    btin.Visible = true;
                    btout.Visible = true;
                    btsendtrayinfo.Visible = true;
                    lbtrayno1.Visible = true;
                    lbstageloc.Visible = true;
                    tbxhandstageloc.Visible = true;
                    btoutinvenory.Visible = true;
                    tbxspecialcreceipe.Visible = true;
                    listboxstageloc.Visible = true;
                    btreserve.Visible = true;
                }
                else
                {
                    HandMode = false;
                    tbxrunmode.Text = "自动中";
                    tbxtrayno1.Visible = false;
                    listboxstageloc.Visible = false;
                    btmove.Visible = false;
                    btin.Visible = false;
                    btout.Visible = false;
                    lbtrayno1.Visible = false;
                    btsendtrayinfo.Visible = false;
                    btoutinvenory.Visible = false;
                    lbstageloc.Visible = false;
                    tbxhandstageloc.Visible = false;
                    tbxspecialcreceipe.Visible = false;
                    listboxstageloc.Visible = false;
                    btreserve.Visible = false;
                }

            }
            else
            { 
           
            }

            
        }

        private void 架台类型设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StageTypeSet stageset = new StageTypeSet();
            stageset.Show();
        }

        private void 工艺设定ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormSECProcessSet processset = new FormSECProcessSet();
            processset.Show();
        }

        private void bt41c_Click(object sender, EventArgs e)
        {
            tbxhandstageloc.Text = lb41sts.Text;
            tbxtrayno1.Text = lb41tray.Text;
        }

        private void bt63c_Click(object sender, EventArgs e)
        {
            //string stagelocation = lb63sts.Text.Substring(0, 1).PadLeft(3, '0') + lb63sts.Text.Substring(2, 1).PadLeft(3, '0') + lb63sts.Text.Substring(4, 1).PadLeft(3, '0');
            tbxhandstageloc.Text = lb63sts.Text;
            tbxtrayno1.Text = lb63tray.Text;
            
            
        }

        private void bt62c_Click(object sender, EventArgs e)
        {
            //string stagelocation = lb62sts.Text.Substring(0, 1).PadLeft(3, '0') + lb62sts.Text.Substring(2, 1).PadLeft(3, '0') + lb62sts.Text.Substring(4, 1).PadLeft(3, '0');
            tbxhandstageloc.Text = lb62sts.Text;
            tbxtrayno1.Text = lb62tray.Text;
        }

        private void bt61c_Click(object sender, EventArgs e)
        {
            //string stagelocation = lb61sts.Text.Substring(0, 1).PadLeft(3, '0') + lb61sts.Text.Substring(2, 1).PadLeft(3, '0') + lb61sts.Text.Substring(4, 1).PadLeft(3, '0');
            tbxhandstageloc.Text = lb61sts.Text;
            tbxtrayno1.Text = lb61tray.Text;
        }

        private void bt53c_Click(object sender, EventArgs e)
        {
            tbxhandstageloc.Text = lb53sts.Text;
            tbxtrayno1.Text = lb53tray.Text;
        }

        private void bt52c_Click(object sender, EventArgs e)
        {
            tbxhandstageloc.Text = lb52sts.Text;
            tbxtrayno1.Text = lb52tray.Text;
        }

        private void bt51c_Click(object sender, EventArgs e)
        {
            tbxhandstageloc.Text = lb51sts.Text;
            tbxtrayno1.Text = lb51tray.Text;
        }

        private void bt43c_Click(object sender, EventArgs e)
        {
            tbxhandstageloc.Text = lb43sts.Text;
            tbxtrayno1.Text = lb43tray.Text;
        }

        private void bt42c_Click(object sender, EventArgs e)
        {
            tbxhandstageloc.Text = lb42sts.Text;
            tbxtrayno1.Text = lb42tray.Text;
        }

        private void bt33c_Click(object sender, EventArgs e)
        {
            tbxhandstageloc.Text = lb33sts.Text;
            tbxtrayno1.Text = lb33tray.Text;
        }

        private void bt32c_Click(object sender, EventArgs e)
        {
            tbxhandstageloc.Text = lb32sts.Text;
            tbxtrayno1.Text = lb32tray.Text;
        }

        private void bt31c_Click(object sender, EventArgs e)
        {
            tbxhandstageloc.Text = lb31sts.Text;
            tbxtrayno1.Text = lb31tray.Text;
        }

        private void bt23tray_Click(object sender, EventArgs e)
        {
            tbxhandstageloc.Text = lb23sts.Text;
            tbxtrayno1.Text = lb23tray.Text;
        }

        private void bt22c_Click(object sender, EventArgs e)
        {
            tbxhandstageloc.Text = lb22sts.Text;
            tbxtrayno1.Text = lb22tray.Text;
        }

        private void bt21c_Click(object sender, EventArgs e)
        {
            tbxhandstageloc.Text = lb21sts.Text;
            tbxtrayno1.Text = lb21tray.Text;
        }

        private void bt13c_Click(object sender, EventArgs e)
        {
            tbxhandstageloc.Text = lb13sts.Text;
            tbxtrayno1.Text = lb13tray.Text;
        }

        private void bt12c_Click(object sender, EventArgs e)
        {
            tbxhandstageloc.Text = lb12sts.Text;
            tbxtrayno1.Text = lb12tray.Text;
        }

        private void bt11c_Click(object sender, EventArgs e)
        {
            tbxhandstageloc.Text = lb11sts.Text;
            tbxtrayno1.Text = lb11tray.Text;
        }

        private void btin_Click(object sender, EventArgs e)
        {

            if (bgmove.IsBusy || bgout.IsBusy || bgin.IsBusy || bgHandOutInventory.IsBusy)
            {
                MessageBox.Show("动作中!");
            }
            else
            {
               
                bgin.RunWorkerAsync();
            }
        }

        private void btmove_Click(object sender, EventArgs e)
        {

            if (bgmove.IsBusy || bgout.IsBusy || bgin.IsBusy ||bgHandOutInventory.IsBusy)
            {
                MessageBox.Show("动作中!");
                return;
            }
            else
            {
               
                bgmove.RunWorkerAsync();
            }
        }

        private void btout_Click(object sender, EventArgs e)
        {
            if (bgmove.IsBusy || bgout.IsBusy || bgin.IsBusy||bgHandOutInventory.IsBusy)
            {
                MessageBox.Show("动作中!");
            }
            else
            {
               
                bgout.RunWorkerAsync();
            }
            
        }

        private void bgmove_DoWork(object sender, DoWorkEventArgs e)
        {
           
            int ActionType = 1;
          
            string fromx = "";
            string froml = "";
            string fromc = "";
            if (!string.IsNullOrEmpty(tbxhandstageloc.Text))
            {
                fromx = tbxhandstageloc.Text.Substring(0, 1);
                froml = tbxhandstageloc.Text.Substring(2, 1);
                fromc = tbxhandstageloc.Text.Substring(4, 1);
            }
            else
            {
                MessageBox.Show("架台号不能为空");
            }
            string rec506 = ReadRightValue4("506", 1, "0001");
            if (rec506 != "0001")
            {

                tbxeqsts.Text = "非正常结束移动失败";
                tbxeqsts.BackColor = Color.Green;

                Log.SystemError.Add("堆垛机上次非正常结束，移动失败");

                return;
            }
            tbxeqsts.Text = "正在移动";
            tbxeqsts.BackColor = Color.SpringGreen;
            WriteRightValue4(30, 1, 6);

            WriteRightValue4(31, 1, ActionType);

            //From 
            WriteRightValue4(32, 1, int.Parse(fromx));
            WriteRightValue4(33, 1, int.Parse(froml));
            WriteRightValue4(34, 1, int.Parse(fromc));

            //更新
            WriteRightValue4(10, 1, 1);

            WriteRightValue4(100, 1, 1);
            //等待W0510是否置1

            string rec510 = ReadRightValue4("510", 1, "0001");


            if (rec510 != "0001")
            {


                Log.SystemError.Add("PLC响应异常,LD待机异常");
                richtbxmsg.AppendText("PLC响应异常,LD待机异常请重新移动\r\n");
                if (rec510 == "0002")
                {
                    tbxeqsts.Text = "LD待机异常\r\n";
                    tbxeqsts.BackColor = Color.Red;
                }
                else if (rec510 == "0003")
                {
                    tbxeqsts.Text = "LD搬送Data异常";
                    tbxeqsts.BackColor = Color.Red;
                }
                else if (rec510 == "0004")
                {
                    tbxeqsts.Text = "LD装载地I/L异常";
                    tbxeqsts.BackColor = Color.Red;
                }
                else if (rec510 == "0005")
                {
                    tbxeqsts.Text = "LD装载下降地I/L异常";
                    tbxeqsts.BackColor = Color.Red;
                }

                WriteRightValue(10, 1, 0);
                return;
            }
            WriteRightValue4(10, 1, 0);
          

            while (ReadRightValue4("511", 1, "notnull") != "0001")
            {
              
                Thread.Sleep(100);
            }
            
            WriteRightValue4(11, 1, 1);
            Thread.Sleep(300);
            if (ReadRightValue4("511", 1, "0000") == "0000")
            {
                WriteRightValue4(11, 1, 0);
            }
            tbxeqsts.Text = "已到达目标架台";
            tbxeqsts.BackColor = Color.SpringGreen;
            tbxeqloc.Text = fromx+"-"+froml+"-"+fromc;
            tbxeqsts.Text = "待机中";
        }

        private void bgout_DoWork(object sender, DoWorkEventArgs e)
        {
            tbl_stageTrayInfoTableAdapter stagetray = new tbl_stageTrayInfoTableAdapter();
            ht_LDTaskListTableAdapter httask = new ht_LDTaskListTableAdapter();
            tbl_stageinfoTableAdapter stageinfo = new tbl_stageinfoTableAdapter();
            string TrayNo = "";
            int ActionType = 2;
            string fromx = "";
            string froml = "";
            string fromc = "";
            if (!string.IsNullOrEmpty(tbxhandstageloc.Text))
            {
                fromx = tbxhandstageloc.Text.Substring(0, 1);
                froml = tbxhandstageloc.Text.Substring(2, 1);
                fromc = tbxhandstageloc.Text.Substring(4, 1);
            }
            else
            {
                MessageBox.Show("架台号不能为空");
            }
            if (fromx == "1" && froml == "9" && fromc == "1")
            {

            }
            else
            {
                int restno = int.Parse(stageinfo.GetRestStageNoByLocation(fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0')).ToString());

                if (restno > 0)
                {
                }
                else
                {
                    MessageBox.Show("当前架台不可以搬出托盘");
                    return;
                }

            }
            //校验口出库不校验是否存在
            if ((fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0')) == "001009002")
            {
                string checksts = ReadRightValue4("1526", 1, "notnull");
                if (checksts != "0001")
                {
                    MessageBox.Show("校验位置没有托盘不能搬出!");
                    return;
                }
            }
            else if ((fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0')) == "001009003")
            {
                MessageBox.Show("搬出口不允许搬出!");
                return;
            }
            else
            {
                //判断是否没有托盘，还在搬入。
                DataTable dtstagetray = new DataTable();
                try
                {
                    dtstagetray = stagetray.GetTrayNoByStageLocation(fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0'));
                }
                catch (Exception ex)
                {
                    richtbxmsg.AppendText("从架台托盘表根据架台号获取托盘号失败\r\n");
                    Log.SystemError.Add("从架台托盘表根据架台号获取托盘号失败" + ex.ToString());
                }

                string trayno1 = "";
                if (dtstagetray.Rows.Count > 0)
                {
                    trayno1 = dtstagetray.Rows[0]["trayno"].ToString();
                    if (string.IsNullOrEmpty(trayno1))
                    {
                        MessageBox.Show("当前架台无托盘，已停止搬出！");
                        return;
                    }


                }
                else
                {
                    richtbxmsg.AppendText("从架台托盘表根据架台获取托盘号信息失败!\r\n");
                    Log.SystemError.Add("从架台托盘表根据架台获取托盘号信息失败!");
                    return;
                }

            }
            

            if (string.IsNullOrEmpty(tbxtrayno1.Text))
            {
                //MessageBox.Show("托盘号不能为空");
                //return;
                DataTable dt1 = httask.GetTrayNoFromHtTask(fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0'));
                if (dt1.Rows.Count > 0)
                {
                    TrayNo = dt1.Rows[0]["trayno"].ToString();
                }
                else
                {
                    TrayNo = "";
                }

                
            }

            string rec506 = ReadRightValue4("506", 1, "0001");
            if (rec506 != "0001")
            {
                tbxeqsts.Text = "非正常结束移动失败";
                tbxeqsts.BackColor = Color.Green;
               
                Log.SystemError.Add("堆垛机上次非正常结束，移动失败");
              
                return;
            }
            tbxeqsts.Text = "正在出库";
            tbxeqsts.BackColor = Color.SpringGreen;
            WriteRightValue4(30, 1, 6);

            WriteRightValue4(31, 1, ActionType);

            //From 
            WriteRightValue4(32, 1, int.Parse(fromx));
            WriteRightValue4(33, 1, int.Parse(froml));
            WriteRightValue4(34, 1, int.Parse(fromc));

           
            //更新
            WriteRightValue4(10, 1, 1);

            WriteRightValue4(100, 1, 1);
            //等待W0510是否置1

            string rec510 = ReadRightValue4("510", 1, "0001");

            if (rec510 != "0001")
            {


                Log.SystemError.Add("PLC响应异常,LD待机异常");
                richtbxmsg.AppendText("PLC响应异常,LD待机异常请重新搬出\r\n");
                if (rec510 == "0002")
                {
                    tbxeqsts.Text = "LD待机异常\r\n";
                    tbxeqsts.BackColor = Color.Red;
                }
                else if (rec510 == "0003")
                {
                    tbxeqsts.Text = "LD搬送Data异常";
                    tbxeqsts.BackColor = Color.Red;
                }
                else if (rec510 == "0004")
                {
                    tbxeqsts.Text = "LD装载地I/L异常";
                    tbxeqsts.BackColor = Color.Red;
                }
                else if (rec510 == "0005")
                {
                    tbxeqsts.Text = "LD装载下降地I/L异常";
                    tbxeqsts.BackColor = Color.Red;
                }

                WriteRightValue(10, 1, 0);
                return;
            }
            WriteRightValue4(10, 1, 0);

            while (ReadRightValue4("511", 1, "notnull") != "0001")
            {
                string str1 = ReadRightValue4("511", 1, "notnull");
                //如果未出库的话才出库

                if (froml.PadLeft(4, '0') == "0009" && fromc.PadLeft(4, '0') == "0001")
                {

                    string rec590 = ReadRightValue4("590", 1, "notnull");
                    string rec591 = ReadRightValue4("591", 1, "notnull");
                    string rec592 = ReadRightValue4("592", 1, "notnull");
                    if (rec590 == fromx.PadLeft(4, '0') && rec591 == froml.PadLeft(4, '0') && rec592 == fromc.PadLeft(4, '0'))
                    {
                        tbxeqloc.Text = rec590.Substring(3, 1) + "-" + rec591.Substring(3, 1) + "-" + rec592.Substring(3, 1);
                        WriteRightValue4(90, 1, int.Parse(fromx.PadLeft(4, '0')));
                        WriteRightValue4(91, 1, int.Parse(froml.PadLeft(4, '0')));
                        WriteRightValue4(92, 1, int.Parse(fromc.PadLeft(4, '0')));

                        Thread.Sleep(600);
                        string rec152A = ReadRightValue4("152A", 1, "notnull");

                        string rec593 = ReadRightValue4("593", 1, "notnull");

                        if (rec152A == "0001" && rec593 == "0002")
                        {
                        
                            tbxeqsts.Text = "出库已就位";
                            tbxeqsts.BackColor = Color.SpringGreen;
                            WriteRightValue4(93, 1, 2);
                            if (ReadRightValue4("593", 1, "0000") == "0000")
                            {
                                WriteRightValue4(93, 1, 0);
                            }
                            else
                            {
                                
                                richtbxmsg.AppendText("PLC异常W0593未复位");
                                Log.SystemError.Add(TrayNo + " W0593未复位");
                            }
                        }
                        else
                        {
                            Log.SystemError.Add("入口销钉下降失败,程序等待中");
                            richtbxmsg.AppendText("入口销钉下降失败,程序等待中\r\n");
                            Thread.Sleep(1000);
                        }
                    }
                }
                else if (froml.PadLeft(4, '0') == "0009" && fromc.PadLeft(4, '0') == "0002")
                {


                    string rec590 = ReadRightValue4("590", 1, "notnull");
                    string rec591 = ReadRightValue4("591", 1, "notnull");
                    string rec592 = ReadRightValue4("592", 1, "notnull");
                   
                    if (rec590 == fromx.PadLeft(4, '0') && rec591 == froml.PadLeft(4, '0') && rec592 == fromc.PadLeft(4, '0'))
                    {
                        tbxeqloc.Text = rec590.Substring(3, 1) + "-" + rec591.Substring(3, 1) + "-" + rec592.Substring(3, 1);
                        WriteRightValue4(90, 1, int.Parse(fromx.PadLeft(4, '0')));
                       
                        WriteRightValue4(91, 1, int.Parse(froml.PadLeft(4, '0')));
                       
                        WriteRightValue4(92, 1, int.Parse(fromc.PadLeft(4, '0')));
                        Thread.Sleep(600);

                        string rec152C = ReadRightValue4("152C", 1, "notnull");
                        string rec593 = ReadRightValue4("593", 1, "notnull");
                        if (rec152C == "0001" && rec593 == "0002")
                        {
                            
                            tbxeqsts.Text = "出库已就位";
                            tbxeqsts.BackColor = Color.SpringGreen;
                            WriteRightValue4(93, 1, 2);
                            Thread.Sleep(200);
                            if (ReadRightValue4("593", 1, "0000") == "0000")
                            {
                                WriteRightValue4(93, 1, 0);
                            }
                            else
                            {
                                
                                richtbxmsg.AppendText("PLC异常W0593未复位");
                                Log.SystemError.Add(TrayNo + " W0593未复位");
                            }
                        }
                        else
                        {
                            Log.SystemError.Add("校验托盘销钉升起失败,程序等待中");
                            richtbxmsg.AppendText("校验托盘销钉升起失败,程序等待中\r\n");
                            Thread.Sleep(1000);
                        }

                        
                    }
                }
                else if (froml.PadLeft(4, '0') != "0009")
                {
                    string rec590 = ReadRightValue4("590", 1, "notnull");
                    string rec591 = ReadRightValue4("591", 1, "notnull");
                    string rec592 = ReadRightValue4("592", 1, "notnull");
                   
                    if (rec590 == fromx.PadLeft(4, '0') && rec591 == froml.PadLeft(4, '0') && rec592 == fromc.PadLeft(4, '0'))
                    {
                        tbxeqloc.Text = rec590.Substring(3, 1) + "-" + rec591.Substring(3, 1) + "-" + rec592.Substring(3, 1);
                        tbxeqsts.Text = "出库已就位";
                        tbxeqsts.BackColor = Color.SpringGreen;
                        WriteRightValue4(90, 1, int.Parse(fromx.PadLeft(4, '0')));
                       
                        WriteRightValue4(91, 1, int.Parse(froml.PadLeft(4, '0')));
                      
                        WriteRightValue4(92, 1, int.Parse(fromc.PadLeft(4, '0')));
                    
                        string rec593 = ReadRightValue4("593", 1, "0002");
                      
                        if (rec593 == "0002")
                        {

                            //WUR
                            bool flag = kep.UpLoadingReservation(fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0'));
                            if (flag == false)
                            {
                                richtbxmsg.AppendText("装载托盘完成，ECS销钉下降失败\r\n");
                                Log.SystemError.Add(TrayNo + "ECS出库销钉下降失败\r\n");
                                //升降钉未下降就持续控制其下降
                                while (flag == false)
                                {
                                    flag = kep.UpLoadingReservation(fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0'));
                                }
                                
                                WriteRightValue4(93, 1, 2);
                                if (ReadRightValue4("593", 1, "0000") == "0000")
                                {
                                    WriteRightValue4(93, 1, 0);
                                    //将架台出库信息同步到stagetrayinfo表

                                    UpdateStageTrayInfo(fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0'), "");
                                    ClearStageTrayInfo(fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0'));
                                    //通知ECS Notify tray unloading completion   WTU
                                    //Thread.Sleep(1500);
                                    bool flag1 = kep.TrayUnload(TrayNo.PadRight(20, ' '), fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0'));

                                    if (!flag1)
                                    {
                                       
                                        Log.SystemError.Add("WTU异常");
                                        richtbxmsg.AppendText("WTU异常\r\n");
                                    }
                                    else
                                    {


                                    }


                                }
                                else
                                {
                                    
                                    Log.SystemError.Add("W0593未复位");
                                  
                                    richtbxmsg.AppendText("PLC异常，请复位PLC\r\n");

                                }
                            }
                            else
                            {

                               
                                WriteRightValue4(93, 1, 2);
                             
                                if (ReadRightValue4("593", 1, "0000") == "0000")
                                {
                                    WriteRightValue4(93, 1, 0);
                                    //将架台出库信息同步到stagetrayinfo表

                                    UpdateStageTrayInfo(fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0'), TrayNo);
                                    //通知ECS Notify tray unloading completion   WTU

                                    bool flag1 = kep.TrayUnload(TrayNo.PadRight(20, ' '), fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0'));

                                    if (!flag1)
                                    {
                                      
                                        Log.SystemError.Add("WTU异常");
                                        richtbxmsg.AppendText("WTU异常\r\n");
                                        ClearStageTrayInfo(fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0'));
                                        
                                    }
                                    else
                                    {
                                       
                                    }


                                }
                                else
                                {
                                
                                    Log.SystemError.Add("W0593未复位");
                                   
                                    richtbxmsg.AppendText("PLC异常，请复位PLC\r\n");

                                }
                            }
                        }
                        else
                        {

                        }
                    }


                }

            }


            WriteRightValue4(11, 1, 1);
            Thread.Sleep(300);
           
            if (ReadRightValue4("511", 1, "0000") == "0000")
            {
                WriteRightValue4(11, 1, 0);
            }
            tbxeqsts.Text = "已完成出库";
            tbxeqsts.BackColor = Color.SpringGreen;
            tbxeqsts.Text = "待机中";
        }

        private void bgin_DoWork(object sender, DoWorkEventArgs e)
        {
            tbl_stageTrayInfoTableAdapter stagetray = new tbl_stageTrayInfoTableAdapter();
            Insertht_askListTableAdapter inserhttask = new Insertht_askListTableAdapter();
            tbl_LDTaskListTableAdapter task = new tbl_LDTaskListTableAdapter();
            tbl_stageinfoTableAdapter stageinfo = new tbl_stageinfoTableAdapter();
            string rec1590 = ReadRightValue4("590", 1, "notnull");
             string rec1591 = ReadRightValue4("591", 1, "notnull");
             string rec1592 = ReadRightValue4("592", 1, "notnull");

            string reservestage = "";
            if (rec1591 != "0009" )
            {
                if (string.IsNullOrEmpty(tbxtrayno1.Text))
                {
                    MessageBox.Show("托盘号不能为空");
                    return;
                }
                DataTable dtstageinfo = stageinfo.GetReservedStageLocation();
                if (dtstageinfo.Rows.Count > 0)
                {
                    reservestage = dtstageinfo.Rows[0]["stagelocation"].ToString();
                    if (reservestage == rec1590.Substring(1, 3) + rec1591.Substring(1, 3) + rec1592.Substring(1, 3))
                    {

                    }
                    else
                    {
                        MessageBox.Show("堆垛机当前架台与预约架台不一致");
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("请提前预约架台!");
                    tbxeqsts.Text = "";
                    tbxeqsts.BackColor = Color.White;
                    return;
                }
            }

            
           
            
            

            string TrayNo = tbxtrayno1.Text;

            
            int ActionType = 3;
            string tox = "";
            string tol = "";
            string toc = "";
            string fromlocation = "001009001";
            string fromx ="";
            string froml ="";
            string fromc ="";
            
            int keyid;
            if (!string.IsNullOrEmpty(tbxhandstageloc.Text))
            {
                tox = tbxhandstageloc.Text.Substring(0, 1);
                tol = tbxhandstageloc.Text.Substring(2, 1);
                toc = tbxhandstageloc.Text.Substring(4, 1);
            }
            else
            {
                MessageBox.Show("架台号不能为空");
            }
            //校验和搬出口入库不校验重复
            if ((tox.PadLeft(3, '0') + tol.PadLeft(3, '0') + toc.PadLeft(3, '0')) != "001009003" && (tox.PadLeft(3, '0') + tol.PadLeft(3, '0') + toc.PadLeft(3, '0')) != "001009002")
            {
                DataTable dtstagetray = new DataTable();
                try
                {
                    dtstagetray = stagetray.GetTrayNoByStageLocation(tox.PadLeft(3, '0') + tol.PadLeft(3, '0') + toc.PadLeft(3, '0'));
                }
                catch (Exception ex)
                {
                    richtbxmsg.AppendText("从架台托盘表根据架台号获取托盘号失败\r\n");
                    Log.SystemError.Add("从架台托盘表根据架台号获取托盘号失败" + ex.ToString());
                }

                string trayno2 = "";
                if (dtstagetray.Rows.Count > 0)
                {
                    trayno2 = dtstagetray.Rows[0]["trayno"].ToString();
                    if (!string.IsNullOrEmpty(trayno2))
                    {
                        MessageBox.Show("当前架台有托盘，已停止搬入！");
                        return;
                    }
                    //判断当前托盘是否在别的架台充放电
                    int traycount = int.Parse(stagetray.GetTrayNoCountByTrayNo(TrayNo).ToString());
                    if (traycount > 0)
                    {
                        MessageBox.Show("当前搬入的托盘已经在其他架台充放电,已停止搬入！");
                        return;
                    }


                }
                else
                {
                    richtbxmsg.AppendText("从架台托盘表根据架台获取托盘号信息失败!\r\n");
                    Log.SystemError.Add("从架台托盘表根据架台获取托盘号信息失败!");
                    return;
                }
            }
            

            string rec506 = ReadRightValue4("506", 1, "0001");
            if (rec506 != "0001")
            {
                tbxeqsts.Text = "非正常结束移动失败";
                tbxeqsts.BackColor = Color.Green;
                Log.SystemError.Add("堆垛机上次非正常结束，移动失败");
                return;
            }
           

            tbxeqsts.Text = "正在入库";
            tbxeqsts.BackColor = Color.SpringGreen;

            WriteRightValue4(30, 1, 6);

            WriteRightValue4(31, 1, ActionType);
            //To的值
            WriteRightValue4(35, 1, int.Parse(tox));
            WriteRightValue4(36, 1, int.Parse(tol));
            WriteRightValue4(37, 1, int.Parse(toc));

            //更新
            WriteRightValue4(10, 1, 1);

            WriteRightValue4(100, 1, 1);
            //等待W0510是否置1

            string rec510 = ReadRightValue4("510", 1, "0001");

            if (rec510 != "0001")
            {


                Log.SystemError.Add("PLC响应异常,LD待机异常");
                richtbxmsg.AppendText("PLC响应异常,LD待机异常,请重新搬入\r\n");
                if (rec510 == "0002")
                {
                    tbxeqsts.Text = "LD待机异常\r\n";
                    tbxeqsts.BackColor = Color.Red;
                }
                else if (rec510 == "0003")
                {
                    tbxeqsts.Text = "LD搬送Data异常";
                    tbxeqsts.BackColor = Color.Red;
                }
                else if (rec510 == "0004")
                {
                    tbxeqsts.Text = "LD装载地I/L异常";
                    tbxeqsts.BackColor = Color.Red;
                }
                else if (rec510 == "0005")
                {
                    tbxeqsts.Text = "LD装载下降地I/L异常";
                    tbxeqsts.BackColor = Color.Red;
                }

                WriteRightValue(10, 1, 0);
                return;
            }
            WriteRightValue4(10, 1, 0);
            while (ReadRightValue4("511", 1, "notnull") != "0001")
            {

                if (tol.PadLeft(4, '0') == "0009" && toc.PadLeft(4, '0') == "0002")
                {

                    string rec590 = ReadRightValue4("590", 1, "notnull");
                    string rec591 = ReadRightValue4("591", 1, "notnull");
                    string rec592 = ReadRightValue4("592", 1, "notnull");
                    if (rec590 == tox.PadLeft(4, '0') && rec591 == tol.PadLeft(4, '0') && rec592 == toc.PadLeft(4, '0'))
                    {
                        tbxeqloc.Text = rec590.Substring(3, 1) + "-" + rec591.Substring(3, 1) + "-" + rec592.Substring(3, 1);
                        WriteRightValue4(90, 1, int.Parse(tox.PadLeft(4, '0')));
                       
                        WriteRightValue4(91, 1, int.Parse(tol.PadLeft(4, '0')));
                       
                        WriteRightValue4(92, 1, int.Parse(toc.PadLeft(4, '0')));
                        Thread.Sleep(500);

                        string rec152C = ReadRightValue4("152C", 1, "notnull");
                        string rec593 = ReadRightValue4("593", 1, "notnull");
                        //判断校验托盘存放位置的销钉是否已经上升。
                        if (rec152C == "0002" && rec593 == "0001")
                        {

                            tbxeqsts.Text = "入库已就位";
                            tbxeqsts.BackColor = Color.SpringGreen;
                            WriteRightValue4(93, 1, 1);
                            if (ReadRightValue4("593", 1, "0000") == "0000")
                            {
                                WriteRightValue4(93, 1, 0);
                                Thread.Sleep(200);
                            }
                        }
                        else
                        {
                            Log.SystemError.Add("校验托盘位置的销钉升起失败,程序等待中");
                            richtbxmsg.AppendText("校验托盘位置的销钉升起失败,程序等待中\r\n");
                            Thread.Sleep(1000);
                        }
                    }


                }
                else if (tol.PadLeft(4, '0') == "0009" && toc.PadLeft(4, '0') == "0003")
                {


                    string rec590 = ReadRightValue4("590", 1, "notnull");
                    string rec591 = ReadRightValue4("591", 1, "notnull");
                    string rec592 = ReadRightValue4("592", 1, "notnull");
                    //Log.WriteLog(LogFile.Trace, "当前堆垛机位置是" + rec590 + "-" + rec591 + "-" + rec592);
                    if (rec590 == tox.PadLeft(4, '0') && rec591 == tol.PadLeft(4, '0') && rec592 == toc.PadLeft(4, '0'))
                    {
                        tbxeqloc.Text = rec590.Substring(3, 1) + "-" + rec591.Substring(3, 1) + "-" + rec592.Substring(3, 1);
                        WriteRightValue4(90, 1, int.Parse(tox.PadLeft(4, '0')));
                        WriteRightValue4(91, 1, int.Parse(tol.PadLeft(4, '0')));
                        WriteRightValue4(92, 1, int.Parse(toc.PadLeft(4, '0')));
                        tbxeqsts.Text = "入库已就位";
                        tbxeqsts.BackColor = Color.SpringGreen;
                        Thread.Sleep(500);
                        string rec593 = ReadRightValue4("593", 1, "notnull");
                        string rec152B = ReadRightValue4("152B", 1, "notnull");
                        //判断校验托盘存放位置的销钉是否已经上升。
                        if (rec152B == "0002" && rec593 == "0001")
                        {

                            WriteRightValue4(93, 1, 1);
                            Thread.Sleep(200);
                            if (ReadRightValue4("593", 1, "0000") == "0000")
                            {
                                WriteRightValue4(93, 1, 0);
                                //Thread.Sleep(200);
                            }
                        }
                        else
                        {
                            Log.SystemError.Add("三层出库位置的销钉升起失败,程序等待中");
                            richtbxmsg.AppendText("三层出库位置的销钉升起失败,程序等待中\r\n");
                            Thread.Sleep(500);
                        }
                    }
                }
                else if (tol.PadLeft(4, '0') != "0009")
                {
                    string rec590 = ReadRightValue4("590", 1, "notnull");
                    string rec591 = ReadRightValue4("591", 1, "notnull");
                    string rec592 = ReadRightValue4("592", 1, "notnull");
                   
                    //Log.WriteLog(LogFile.Trace, "当前堆垛机位置是" + rec590 + "-" + rec591 + "-" + rec592);
                    //先验证入库位置是否正确
                    if (rec590 == tox.PadLeft(4, '0') && rec591 == tol.PadLeft(4, '0') && rec592 == toc.PadLeft(4, '0'))
                    {
                        tbxeqloc.Text = rec590.Substring(3, 1) + "-" + rec591.Substring(3, 1) + "-" + rec592.Substring(3, 1);
                        tbxeqsts.Text = "入库已就位";
                        tbxeqsts.BackColor = Color.SpringGreen;
                        //即使手动也要生成任务
                        string traytype = TrayNo.Substring(TrayNo.Length - 3, 3);
                        string recipeid = GetRecipeID(traytype);
                        if (string.IsNullOrEmpty(recipeid))
                        {
                            richtbxmsg.AppendText("请设置正确的托盘类型对应的配方号\r\n");

                            continue;
                        }

                        short actionid = 120;   //待定
                        short actiontype = 4;
                        short priority = 1;

                        string usr = "m001";

                        string tolocation = "";
                        bool insertflag = false;
                        int reserveno = int.Parse(stageinfo.GetIfReserved().ToString());
                        if (reserveno > 0)
                        {
                            DataTable dt = stageinfo.GetReservedStageLocation();
                            if (dt.Rows.Count > 0)
                            {
                                tolocation = dt.Rows[0]["stagelocation"].ToString();
                                tox = tolocation.Substring(0, 3);
                                tol = tolocation.Substring(3, 3);
                                toc = tolocation.Substring(6, 3);
                            }

                        }
                        else
                        {
                            continue;
                        }


                        

                        try
                        {

                            task.InsertTask(TrayNo, recipeid, actionid, actiontype, fromlocation, fromx, froml, fromc, tolocation, tox, tol, toc, priority, null, "m", usr, DateTime.Now, null, null, null, 1);
                            richtbxmsg.AppendText(TrayNo + "生成任务成功!\r\n");
                            insertflag = true;

                        }
                        catch (Exception)
                        {
                            richtbxmsg.AppendText("保存任务失败,可能是由于格式不正确导致的\r\n");
                            while (insertflag == false)
                            {
                                try
                                {

                                    task.InsertTask(TrayNo, recipeid, actionid, actiontype, fromlocation, fromx, froml, fromc, tolocation, tox, tol, toc, priority, null, "m", usr, DateTime.Now, null, null, null, 1);
                                    insertflag = true;

                                }
                                catch (Exception)
                                {
                                }
                            }
                        }
                        WriteRightValue4(90, 1, int.Parse(tox.PadLeft(4, '0')));

                        WriteRightValue4(91, 1, int.Parse(tol.PadLeft(4, '0')));

                        WriteRightValue4(92, 1, int.Parse(toc.PadLeft(4, '0')));

                        string rec593 = ReadRightValue4("593", 1, "0001");
                        //Thread.Sleep(200);
                        if (rec593 == "0001")
                        {
                            //先清下之前已有的ETL
                            GParam.RecStringDic["ETL"] = "";
                            for (int i = 0; i < GParam.RecListDic["ETL"].Count; i++)
                            {
                                GParam.RecListDic["ETL"].RemoveAt(0);
                            }
                            Thread.Sleep(700);
                            string stageloc = tox.PadLeft(3, '0') + tol.PadLeft(3, '0') + toc.PadLeft(3, '0');
                            bool flag = kep.TrayLoad(TrayNo, stageloc);
                            bool ETLWrong = false;

                            if (flag == false)
                            {
                                richtbxmsg.AppendText("由于ECS销钉升起失败，等待人工处理中\r\n");
                                Log.WriteLog(LogFile.SystemError, TrayNo + "入库升降钉升起失败");
                                ETLWrong = true;
                                while (!(GParam.RecListDic.ContainsKey("ETL") && GParam.RecStringDic.ContainsKey("ETL") && GParam.RecStringDic["ETL"].Length > 0 && GParam.RecStringDic["ETL"].Substring(17, 1) == "1"))
                                {
                                    GParam.RecStringDic["ETL"] = "";
                                    for (int i = 0; i < GParam.RecListDic["ETL"].Count; i++)
                                    {
                                        GParam.RecListDic["ETL"].RemoveAt(0);
                                    }
                                    

                                    

                                    Thread.Sleep(1000);
                                }

                            }

                            if (ETLWrong == true)
                            {
                                //销钉升起成功，即将回复WTL
                                GParam.RecStringDic["ETL"] = "";
                                string stageloc1 = GParam.RecListDic["ETL"][0].ToString().Substring(8, 9);
                                string trayno1 = "";
                                trayno1 = TrayNo;

                                bool flag1 = kep.TrayLoad(trayno1, stageloc);
                                if (flag1 == true)
                                {
                                    richtbxmsg.AppendText("已解除故障，销钉已升起，即将开始充电\r\n");
                                    Log.SystemError.Add("已解除故障，销钉已升起，即将开始充电");

                                    //需要清空ETL的RecListDic
                                    //将架台,托盘信息存储到数据库中
                                    UpdateStageTrayInfo(stageloc, trayno1);
                                    ShowStageTrayInfo(stageloc1, trayno1);
                                }
                                else
                                {
                                    while (flag1 == false)
                                    {
                                        flag1 = kep.TrayLoad(trayno1, stageloc);
                                    }

                                }
                                if (GParam.RecListDic["ETL"].Count > 0)
                                {
                                    GParam.RecListDic["ETL"].RemoveAt(0);
                                }

                            }
                            else
                            {

                            }
                            //回复升降钉升起成功

                            WriteRightValue4(93, 1, 1);
                            Thread.Sleep(200);
                            if (ReadRightValue4("593", 1, "0000") == "0000")
                            {
                                WriteRightValue4(93, 1, 0);
                                Thread.Sleep(200);


                            }

                          
                            //将当前任务存到历史任务中
                            //string rec560 = ReadRightValue4("560", 1, "0006");
                            //string rec561 = ReadRightValue4("561", 1, ActionType.ToString().PadLeft(4, '0'));

                            //string rec562 = ReadRightValue4("562", 1, fromx.PadLeft(4, '0'));
                            //string rec563 = ReadRightValue4("563", 1, froml.PadLeft(4, '0'));
                            //string rec564 = ReadRightValue4("564", 1, fromc.PadLeft(4, '0'));

                            //string rec565 = ReadRightValue4("565", 1, tox.PadLeft(4, '0'));
                            //string rec566 = ReadRightValue4("566", 1, tol.PadLeft(4, '0'));
                            //string rec567 = ReadRightValue4("567", 1, toc.PadLeft(4, '0'));

                            string endcode = ReadRightValue4("568", 1, "notnull");
                            short endtype = 1;

                            if (endcode == "0001")
                            {
                                endtype = 0;
                                //if (rec560 == "0006" && rec561 == ActionType.ToString().PadLeft(4, '0') && rec562 == fromx.PadLeft(4, '0') && rec563 == froml.PadLeft(4, '0') && rec564 == fromc.PadLeft(4, '0') && rec565 == tox.PadLeft(4, '0') && rec566 == tol.PadLeft(4, '0') && rec567 == toc.PadLeft(4, '0'))
                                //{
                                //}
                                //else
                                //{
                                //    Log.SystemError.Add(TrayNo + "堆垛机动作类型和动作ID与之前的不一致");
                                //}

                            }
                            else if (endcode == "0002")
                            {

                                tbxeqsts.Text = "堆垛机异常结束";
                                tbxeqsts.BackColor = Color.SpringGreen;
                            }

                            else if (endcode == "0003")
                            {
                                tbxeqsts.Text = "堆垛机运行未结束(无装载)";
                                tbxeqsts.BackColor = Color.SpringGreen;
                            }

                            else if (endcode == "0004")
                            {
                                tbxeqsts.Text = "堆垛机运行未结束(有装载)";
                                tbxeqsts.BackColor = Color.SpringGreen;
                            }

                            //发送托盘信息
                            if (tol.PadLeft(3, '0') != "009")
                            {
                                kep.SendTrayInfo(tox.PadLeft(3, '0') + tol.PadLeft(3, '0') + toc.PadLeft(3, '0'), TrayNo, "");
                            }
                            
                            //获取刚创建的任务的keyid
                            DataTable dttask = task.GetTaskinfoByTrayNo(TrayNo);
                            if (dttask.Rows.Count > 0)
                            {
                                keyid = int.Parse(dttask.Rows[0]["keyid"].ToString());
                                try
                                {
                                    inserhttask.Insertht_LDTaskList(keyid, short.Parse(endcode), endtype, "a001", DateTime.Now);
                                }
                                catch (Exception)
                                {
                                    //Log.WriteLog(LogFile.SystemError,TrayNo+"将任务存入历史任务表失败");
                                    Log.SystemError.Add(TrayNo + "将任务存入历史任务表失败");
                                }
                            }
                          
                           


                        }




                    }
                }

            }
            //while end
            WriteRightValue4(11, 1, 1);
            Thread.Sleep(300);
            if (ReadRightValue4("511", 1, "0000") == "0000")
            {
                WriteRightValue4(11, 1, 0);

            }
            tbxeqsts.Text = "已完成入库";
            tbxeqsts.BackColor = Color.SpringGreen;
            
        }

        private void 修改密码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormChangePass changepass = new FormChangePass();
            changepass.Show();
        }

        private void 查询历史任务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormSearchHtTask httask = new FormSearchHtTask();
            httask.Show();
        }
        private void bgReplayETI_DoWork(object sender, DoWorkEventArgs e)
        {
            //while (true)
            //{

            //    if (GParam.RecListDic.ContainsKey("ETI") && GParam.RecStringDic.ContainsKey("ETI") && GParam.RecStringDic["ETI"].Length > 0)
            //    {
            //        Log.Trace.Add("已获取到托盘信息请求，托盘请求个数是" + GParam.RecListDic["ETI"].Count);
            //        bool flag = kep.SendTrayInfo();
            //        if (flag == false)
            //        {
            //            MessageBox.Show("从服务器根据托盘号获取电池信息或获取托盘编号失败，请手动扫码！");
            //        }

            //    }
            //    Thread.Sleep(500);
            //}
        }



        //此线程用来回复互成托盘去向
        private void bgReplayTrayForward_DoWork(object sender, DoWorkEventArgs e)
        {
            //DataTable dtInLineTrayNo = new DataTable();
            //while (true)
            //{
            //    dtInLineTrayNo = lp.GetFreeTrayNo();
            //    if (dtInLineTrayNo.Rows.Count > 0)
            //    {
            //        for (int i = 0; i < dtInLineTrayNo.Rows.Count; i++)
            //        {
            //            int nid = int.Parse(dtInLineTrayNo.Rows[i]["nid"].ToString());
            //            string trayno = dtInLineTrayNo.Rows[i]["cPalletId"].ToString();
            //            AllowTrayIn(trayno, nid);
            //        }
            //        dtInLineTrayNo.Clear();
            //    }
            //    Thread.Sleep(500);
            //}

        }

        private void btsendtrayinfo_Click(object sender, EventArgs e)
        {
            tbl_stageTrayInfoTableAdapter stagetray = new tbl_stageTrayInfoTableAdapter();
            string stageloc="";
            string tox="";
            string tol="";
            string toc="";
            int ngcount=0;
            int allowcount=3;
            string receipeid = "";
            if (listboxstageloc.SelectedItems.Count>0)
            {
                receipeid = listboxstageloc.SelectedItem.ToString();
            }
            else
            {
                receipeid = "";
            }
            

            if (!string.IsNullOrEmpty(tbxhandstageloc.Text))
            {
                tox = tbxhandstageloc.Text.Substring(0, 1);
                tol = tbxhandstageloc.Text.Substring(2, 1);
                toc = tbxhandstageloc.Text.Substring(4, 1);
            }
            else
            {
                MessageBox.Show("架台号不能为空");
            }
            //判断当前架台托盘号与发送的是否一致
            DataTable dttrayno = new DataTable();
            try
            {
                dttrayno = stagetray.GetTrayNoByStageLocation(tox.PadLeft(3, '0') + tol.PadLeft(3, '0') + toc.PadLeft(3, '0'));
                ngcount++;
            }
            catch (Exception ex)
            {

                Log.SystemError.Add("从架台托盘号表根据架台获取托盘号失败"+ex.ToString());
                ngcount++;
            }

            while (dttrayno.Rows.Count <= 0 && ngcount < allowcount)
            {
                dttrayno = stagetray.GetTrayNoByStageLocation(tox.PadLeft(3, '0') + tol.PadLeft(3, '0') + toc.PadLeft(3, '0'));
                ngcount++;
            }

            if (dttrayno.Rows.Count > 0)
            {

                string trayno1 = dttrayno.Rows[0]["trayno"].ToString();
                if (trayno1 != tbxtrayno1.Text)
                {
                    MessageBox.Show("发送的托盘号与搬入的托盘号不一致,请核实!");
                    return;
                }
            }
            else
            {
                richtbxmsg.AppendText("从架台托盘号表根据架台获取托盘号失败\r\n");
                Log.SystemError.Add("从架台托盘号表根据架台获取托盘号失败" );
                return;
            }
            stageloc = tox.PadLeft(3, '0') + tol.PadLeft(3,'0')+toc.PadLeft(3,'0');
            bool ETIFlag = kep.SendTrayInfo(stageloc, tbxtrayno1.Text, receipeid);
            if (ETIFlag == false)
            {
                richtbxmsg.AppendText("发送托盘信息失败，请检查该托盘是否是实验电池！\r\n");
                Log.SystemError.Add("发送托盘信息失败，可能是由于获取工艺号或本托盘的电池条码失败导致的!");
            }
            MessageBox.Show("发送托盘信息成功!");
        }

        private void btCheckEqIn_Click(object sender, EventArgs e)
        {
            bgCheckEqIn.RunWorkerAsync();

        }

        private void bgCheckEqIn_DoWork(object sender, DoWorkEventArgs e)
        {
            Insertht_askListTableAdapter inserhttask = new Insertht_askListTableAdapter();
            tbl_LDTaskListTableAdapter task = new tbl_LDTaskListTableAdapter();
            tbl_stageinfoTableAdapter stageinfo = new tbl_stageinfoTableAdapter();
            //if (string.IsNullOrEmpty(tbxtrayno1.Text))
            //{
            //    MessageBox.Show("托盘号不能为空");
            //    return;
            //}
            string rec1590 = ReadRightValue4("590", 1, "notnull");
            string rec1591 = ReadRightValue4("591", 1, "notnull");
            string rec1592 = ReadRightValue4("592", 1, "notnull");

            string reservestage = "";
            if (rec1591 != "0009")
            {
                DataTable dtstageinfo = stageinfo.GetReservedStageLocation();
                if (dtstageinfo.Rows.Count > 0)
                {
                    reservestage = dtstageinfo.Rows[0]["stagelocation"].ToString();
                    if (reservestage == rec1590.Substring(1, 3) + rec1591.Substring(1, 3) + rec1592.Substring(1, 3))
                    {

                    }
                    else
                    {
                        MessageBox.Show("堆垛机当前架台与预约架台不一致");
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("请提前预约架台!");
                    tbxeqsts.Text = "";
                    tbxeqsts.BackColor = Color.White;
                    return;
                }
            }






            string TrayNo = tbxtrayno1.Text;
            int ActionType = 3;
            string tox = "";
            string tol = "";
            string toc = "";
            string fromlocation = "001009001";
            string fromx = "001";
            string froml = "009";
            string fromc = "001";
            int keyid;
            if (!string.IsNullOrEmpty(listboxstageloc.SelectedItem.ToString()))
            {
                tox = listboxstageloc.SelectedItem.ToString().Substring(0, 1);
                tol = listboxstageloc.SelectedItem.ToString().Substring(2, 1);
                toc = listboxstageloc.SelectedItem.ToString().Substring(4, 1);
            }
            else
            {
                MessageBox.Show("架台号不能为空");
            }

            string rec506 = ReadRightValue4("506", 1, "0001");
            if (rec506 != "0001")
            {
                //richtbxmsg.Text = "堆垛机非待机状态";
                richtbxmsg.AppendText("堆垛机上次非正常结束移动失败\r\n");
                //Log.WriteLog(LogFile.Trace,"堆垛机上次非正常结束，"+TrayNo+"搬送失败");
                Log.SystemError.Add("堆垛机上次非正常结束，移动失败");
                //Thread.Sleep(5000);
                return;
            }

            WriteRightValue4(30, 1, 6);

            WriteRightValue4(31, 1, ActionType);

            ////From 
            //WriteRightValue4(32, 1, int.Parse(tox));
            //WriteRightValue4(33, 1, int.Parse(tol));
            //WriteRightValue4(34, 1, int.Parse(toc));

            //To的值
            WriteRightValue4(35, 1, int.Parse(tox));
            WriteRightValue4(36, 1, int.Parse(tol));
            WriteRightValue4(37, 1, int.Parse(toc));

            //更新
            WriteRightValue4(10, 1, 1);

            WriteRightValue4(100, 1, 1);
            //等待W0510是否置1

            string rec510 = ReadRightValue4("510", 1, "0001");

            if (rec510 != "0001")
            {

                Log.SystemError.Add("PLCW510响应异常");

                richtbxmsg.AppendText("PLCW510响应异常\r\n");
                return;
            }
            WriteRightValue4(10, 1, 0);

            //string ldstatus = "";

            while (ReadRightValue4("511", 1, "notnull") != "0001")
            {

                if (tol.PadLeft(4, '0') == "0009" && toc.PadLeft(4, '0') == "0002")
                {

                    string rec590 = ReadRightValue4("590", 1, "notnull");
                    //Thread.Sleep(200);
                    string rec591 = ReadRightValue4("591", 1, "notnull");
                    //Thread.Sleep(200);
                    string rec592 = ReadRightValue4("592", 1, "notnull");
                    //Thread.Sleep(200);

                    if (rec590 == tox.PadLeft(4, '0') && rec591 == tol.PadLeft(4, '0') && rec592 == toc.PadLeft(4, '0'))
                    {
                        tbxeqloc.Text = rec590.Substring(3, 1) + "-" + rec591.Substring(3, 1) + "-" + rec592.Substring(3, 1);
                        WriteRightValue4(90, 1, int.Parse(tox.PadLeft(4, '0')));
                        //Thread.Sleep(200);
                        WriteRightValue4(91, 1, int.Parse(tol.PadLeft(4, '0')));
                        //Thread.Sleep(200);
                        WriteRightValue4(92, 1, int.Parse(toc.PadLeft(4, '0')));
                        Thread.Sleep(500);

                        string rec152C = ReadRightValue4("152C", 1, "notnull");
                        string rec593 = ReadRightValue4("593", 1, "notnull");
                        //判断校验托盘存放位置的销钉是否已经上升。
                        if (rec152C == "0002" && rec593 == "0001")
                        {

                            tbxeqsts.Text = "入库已就位";
                            tbxeqsts.BackColor = Color.SpringGreen;
                            WriteRightValue4(93, 1, 1);
                            //Thread.Sleep(200);
                            if (ReadRightValue4("593", 1, "0000") == "0000")
                            {
                                WriteRightValue4(93, 1, 0);
                                Thread.Sleep(200);
                            }
                        }
                        else
                        {
                            Log.SystemError.Add("校验托盘位置的销钉升起失败,程序等待中");
                            richtbxmsg.AppendText("校验托盘位置的销钉升起失败,程序等待中\r\n");
                            Thread.Sleep(1000);
                        }
                    }


                }
                else if (tol.PadLeft(4, '0') == "0009" && toc.PadLeft(4, '0') == "0003")
                {


                    string rec590 = ReadRightValue4("590", 1, "notnull");
                    //Thread.Sleep(200);
                    string rec591 = ReadRightValue4("591", 1, "notnull");
                    //Thread.Sleep(200);
                    string rec592 = ReadRightValue4("592", 1, "notnull");
                    //Thread.Sleep(200);
                    //Log.WriteLog(LogFile.Trace, "当前堆垛机位置是" + rec590 + "-" + rec591 + "-" + rec592);
                    if (rec590 == tox.PadLeft(4, '0') && rec591 == tol.PadLeft(4, '0') && rec592 == toc.PadLeft(4, '0'))
                    {
                        tbxeqloc.Text = rec590.Substring(3, 1) + "-" + rec591.Substring(3, 1) + "-" + rec592.Substring(3, 1);
                        WriteRightValue4(90, 1, int.Parse(tox.PadLeft(4, '0')));
                        //Thread.Sleep(200);
                        WriteRightValue4(91, 1, int.Parse(tol.PadLeft(4, '0')));
                        //Thread.Sleep(200);
                        WriteRightValue4(92, 1, int.Parse(toc.PadLeft(4, '0')));


                        //richtbxmsg.Text = "入库" + rec590 + "-" + rec591 + "-" + rec592 + "已就位";
                        //richtbxmsg.AppendText("入库" + rec590 + "-" + rec591 + "-" + rec592 + "已就位\r\n");
                        tbxeqsts.Text = "入库已就位";
                        tbxeqsts.BackColor = Color.SpringGreen;
                        Thread.Sleep(500);
                        string rec593 = ReadRightValue4("593", 1, "notnull");
                        string rec152B = ReadRightValue4("152B", 1, "notnull");
                        //判断校验托盘存放位置的销钉是否已经上升。
                        if (rec152B == "0002" && rec593 == "0001")
                        {

                            WriteRightValue4(93, 1, 1);
                            Thread.Sleep(200);
                            if (ReadRightValue4("593", 1, "0000") == "0000")
                            {
                                WriteRightValue4(93, 1, 0);
                                //Thread.Sleep(200);
                            }
                        }
                        else
                        {
                            Log.SystemError.Add("三层出库位置的销钉升起失败,程序等待中");
                            richtbxmsg.AppendText("三层出库位置的销钉升起失败,程序等待中\r\n");
                            Thread.Sleep(500);
                        }
                    }
                }
                else if (tol.PadLeft(4, '0') != "0009")
                {
                    string rec590 = ReadRightValue4("590", 1, "notnull");
                    string rec591 = ReadRightValue4("591", 1, "notnull");
                    string rec592 = ReadRightValue4("592", 1, "notnull");

                    //Log.WriteLog(LogFile.Trace, "当前堆垛机位置是" + rec590 + "-" + rec591 + "-" + rec592);
                    //先验证入库位置是否正确
                    if (rec590 == tox.PadLeft(4, '0') && rec591 == tol.PadLeft(4, '0') && rec592 == toc.PadLeft(4, '0'))
                    {
                        tbxeqloc.Text = rec590.Substring(3, 1) + "-" + rec591.Substring(3, 1) + "-" + rec592.Substring(3, 1);
                        tbxeqsts.Text = "入库已就位";
                        tbxeqsts.BackColor = Color.SpringGreen;
                        //即使手动也要生成任务
                        string traytype = TrayNo.Substring(TrayNo.Length - 3, 3);
                        string recipeid = GetRecipeID(traytype);
                        if (string.IsNullOrEmpty(recipeid))
                        {
                            richtbxmsg.AppendText("请设置正确的托盘类型对应的配方号\r\n");

                            continue;
                        }

                        short actionid = 120;   //待定
                        short actiontype = 4;
                        short priority = 1;

                        string usr = "m001";

                        string tolocation = "";
                        bool insertflag = false;
                        int reserveno = int.Parse(stageinfo.GetIfReserved().ToString());
                        if (reserveno > 0)
                        {
                            DataTable dt = stageinfo.GetReservedStageLocation();
                            if (dt.Rows.Count > 0)
                            {
                                tolocation = dt.Rows[0]["stagelocation"].ToString();
                                tox = tolocation.Substring(0, 3);
                                tol = tolocation.Substring(3, 3);
                                toc = tolocation.Substring(6, 3);
                            }

                        }
                        else
                        {
                            continue;
                        }




                        try
                        {

                            task.InsertTask(TrayNo, recipeid, actionid, actiontype, fromlocation, fromx, froml, fromc, tolocation, tox, tol, toc, priority, null, "m", usr, DateTime.Now, null, null, null, 1);
                            //保存成功任务后lock架台
                            //stageinfo.UpdateLockStage(tolocation);
                            richtbxmsg.AppendText(TrayNo + "生成任务成功!\r\n");
                            //TrayNo = "";
                            insertflag = true;

                        }
                        catch (Exception)
                        {
                            richtbxmsg.AppendText("保存任务失败,可能是由于格式不正确导致的\r\n");
                            while (insertflag == false)
                            {
                                try
                                {

                                    task.InsertTask(TrayNo, recipeid, actionid, actiontype, fromlocation, fromx, froml, fromc, tolocation, tox, tol, toc, priority, null, "m", usr, DateTime.Now, null, null, null, 1);
                                    insertflag = true;

                                }
                                catch (Exception)
                                {
                                }
                            }
                        }
                        WriteRightValue4(90, 1, int.Parse(tox.PadLeft(4, '0')));

                        WriteRightValue4(91, 1, int.Parse(tol.PadLeft(4, '0')));

                        WriteRightValue4(92, 1, int.Parse(toc.PadLeft(4, '0')));

                        string rec593 = ReadRightValue4("593", 1, "0001");
                        //Thread.Sleep(200);
                        if (rec593 == "0001")
                        {
                            //先清下之前已有的ETL
                            GParam.RecStringDic["ETL"] = "";
                            for (int i = 0; i < GParam.RecListDic["ETL"].Count; i++)
                            {
                                GParam.RecListDic["ETL"].RemoveAt(0);
                            }
                            Thread.Sleep(700);
                            string stageloc = tox.PadLeft(3, '0') + tol.PadLeft(3, '0') + toc.PadLeft(3, '0');
                            bool flag = kep.TrayLoad(TrayNo, stageloc);
                            bool ETLWrong = false;

                            if (flag == false)
                            {
                                richtbxmsg.AppendText("由于ECS销钉升起失败，等待人工处理中\r\n");
                                Log.WriteLog(LogFile.SystemError, TrayNo + "入库升降钉升起失败");
                                ETLWrong = true;
                                while (!(GParam.RecListDic.ContainsKey("ETL") && GParam.RecStringDic.ContainsKey("ETL") && GParam.RecStringDic["ETL"].Length > 0 && GParam.RecStringDic["ETL"].Substring(17, 1) == "1"))
                                {
                                    GParam.RecStringDic["ETL"] = "";
                                    for (int i = 0; i < GParam.RecListDic["ETL"].Count; i++)
                                    {
                                        GParam.RecListDic["ETL"].RemoveAt(0);
                                    }




                                    Thread.Sleep(1000);
                                }

                            }

                            if (ETLWrong == true)
                            {
                                //销钉升起成功，即将回复WTL
                                GParam.RecStringDic["ETL"] = "";
                                string stageloc1 = GParam.RecListDic["ETL"][0].ToString().Substring(8, 9);
                                string trayno1 = "";
                                trayno1 = TrayNo;

                                bool flag1 = kep.TrayLoad(trayno1, stageloc);
                                if (flag1 == true)
                                {
                                    richtbxmsg.AppendText("已解除故障，销钉已升起，即将开始充电\r\n");
                                    Log.SystemError.Add("已解除故障，销钉已升起，即将开始充电");

                                    //需要清空ETL的RecListDic
                                    //将架台,托盘信息存储到数据库中
                                    UpdateStageTrayInfo(stageloc, trayno1);
                                    ShowStageTrayInfo(stageloc1, trayno1);
                                }
                                else
                                {
                                    while (flag1 == false)
                                    {
                                        flag1 = kep.TrayLoad(trayno1, stageloc);
                                    }

                                }
                                if (GParam.RecListDic["ETL"].Count > 0)
                                {
                                    GParam.RecListDic["ETL"].RemoveAt(0);
                                }

                            }
                            else
                            {

                            }
                            //回复升降钉升起成功

                            WriteRightValue4(93, 1, 1);
                            Thread.Sleep(200);
                            if (ReadRightValue4("593", 1, "0000") == "0000")
                            {
                                WriteRightValue4(93, 1, 0);
                                Thread.Sleep(200);


                            }


                            //将当前任务存到历史任务中
                            //string rec560 = ReadRightValue4("560", 1, "0006");
                            //string rec561 = ReadRightValue4("561", 1, ActionType.ToString().PadLeft(4, '0'));

                            //string rec562 = ReadRightValue4("562", 1, fromx.PadLeft(4, '0'));
                            //string rec563 = ReadRightValue4("563", 1, froml.PadLeft(4, '0'));
                            //string rec564 = ReadRightValue4("564", 1, fromc.PadLeft(4, '0'));

                            //string rec565 = ReadRightValue4("565", 1, tox.PadLeft(4, '0'));
                            //string rec566 = ReadRightValue4("566", 1, tol.PadLeft(4, '0'));
                            //string rec567 = ReadRightValue4("567", 1, toc.PadLeft(4, '0'));

                            string endcode = ReadRightValue4("568", 1, "notnull");
                            short endtype = 1;

                            if (endcode == "0001")
                            {
                                endtype = 0;
                                //if (rec560 == "0006" && rec561 == ActionType.ToString().PadLeft(4, '0') && rec562 == fromx.PadLeft(4, '0') && rec563 == froml.PadLeft(4, '0') && rec564 == fromc.PadLeft(4, '0') && rec565 == tox.PadLeft(4, '0') && rec566 == tol.PadLeft(4, '0') && rec567 == toc.PadLeft(4, '0'))
                                //{
                                //}
                                //else
                                //{
                                //    Log.SystemError.Add(TrayNo + "堆垛机动作类型和动作ID与之前的不一致");
                                //}

                            }
                            else if (endcode == "0002")
                            {

                                tbxeqsts.Text = "堆垛机异常结束";
                                tbxeqsts.BackColor = Color.SpringGreen;
                            }

                            else if (endcode == "0003")
                            {
                                tbxeqsts.Text = "堆垛机运行未结束(无装载)";
                                tbxeqsts.BackColor = Color.SpringGreen;
                            }

                            else if (endcode == "0004")
                            {
                                tbxeqsts.Text = "堆垛机运行未结束(有装载)";
                                tbxeqsts.BackColor = Color.SpringGreen;
                            }

                           

                            //获取刚创建的任务的keyid
                            DataTable dttask = task.GetTaskinfoByTrayNo(TrayNo);
                            if (dttask.Rows.Count > 0)
                            {
                                keyid = int.Parse(dttask.Rows[0]["keyid"].ToString());
                                try
                                {
                                    inserhttask.Insertht_LDTaskList(keyid, short.Parse(endcode), endtype, "a001", DateTime.Now);
                                }
                                catch (Exception)
                                {
                                    //Log.WriteLog(LogFile.SystemError,TrayNo+"将任务存入历史任务表失败");
                                    Log.SystemError.Add(TrayNo + "将任务存入历史任务表失败");
                                }
                            }




                        }




                    }
                }

            }
            //while end
            WriteRightValue4(11, 1, 1);
            Thread.Sleep(300);
            if (ReadRightValue4("511", 1, "0000") == "0000")
            {
                WriteRightValue4(11, 1, 0);

            }
            tbxeqsts.Text = "已完成入库";
            tbxeqsts.BackColor = Color.SpringGreen;
        }

        private void bgSlave_DoWork(object sender, DoWorkEventArgs e)
        {
            eqstatuscheck();
        }

        //生存确认
        public  void eqstatuscheck()
        {


            //string Hex = "";
            //string Dec="";
            //int b = Int32.Parse(Hex, System.Globalization.NumberStyles.HexNumber);
            //int a = Int32.Parse(Dec, System.Globalization.NumberStyles.);
            //W0000开始写1
            //string checkcode = "500000FF03FF00001C001014010000W*0000000001";
            int i = 0;
            for (i = 0; i <= 65535; )
            {

                if (i >= 65535)
                {
                    i = 1;
                }
                else
                {
                    i = i + 1;
                }

                string temp0 = Convert.ToString(i, 16);
                //temp0 = st1.CovASCToDex(temp0);

                string temp = temp0.ToString().PadLeft(4, '0');

                WriteRightValueForSlave("0000", 1, temp);
                
                //Thread.Sleep(100);
                string checksend = ReadRightValueForSlave("0500", 1, temp);

                    if (checksend == temp)
                    {
                        //st1.ClosedClient(ip,port);
                        //确认成功
                    }
                    else
                    {

                        tbxeqsts.Text = "与PLC连接中断";
                        tbxeqsts.BackColor = Color.Red;
                    }

            }



        }

        private void 数据管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 工艺类型设定ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormNormalProcessSet pt = new FormNormalProcessSet();
            pt.Show();
        }



        ////允许进入return true else false
        //public void AllowTrayIn(string trayno, int nid)
        //{

        //    //先判断在途数量是否和实际数量一致
        //    string st1sts = ReadRightValue5("1520", 1, "notnull");
        //    string st2sts = ReadRightValue5("1521", 1, "notnull");
        //    //onway15no = 0;
        //    //onway19no = 1;

        //    //string st1sts = "0000";
        //    //string st2sts = "0001";

        //    if (!(st1sts == "0001" && st2sts == "0001"))
        //    {//st1,st2不都是占用
        //        string traytype = trayno.Substring(trayno.Length - 3, 3);
        //        //将C12转化成C15
        //        if (traytype == "C12" || traytype == "C15")
        //        {
        //            traytype = "C15";
        //        }
        //        else if (traytype == "C19")
        //        {
        //            traytype = "C19";
        //        }
        //        //获取对应类型架台的数量
        //        int stageno = int.Parse(stageinfo.GetFreeStageNoByRecipeid(traytype).ToString());
        //        if (stageno <= 0)
        //        {
        //            return;
        //        }



        //        //判断在途数量是否和st1，st2占用数量一致，如果不一致需要校正，也就是将st1,2全部搬送完成后再允许新托盘进入
        //        //st1占用，st2不占用
        //        if (st1sts == "0001" && st2sts != "0001")
        //        {
        //            if (onway15no == 1 && onway19no == 0)
        //            {
        //                if (traytype == "C15")
        //                {
        //                    if ((stageno - 1) > 0)
        //                    {
        //                        lp.UpdateTrayForwardByNid(1, nid);
        //                        onway15no++;
        //                    }
        //                    else
        //                    {
        //                        lp.UpdateTrayForwardByNid(2, nid);
        //                    }
        //                }
        //                else
        //                {
        //                    lp.UpdateTrayForwardByNid(1, nid);
        //                    if (traytype == "C15")
        //                    {
        //                        onway15no++;
        //                    }
        //                    else
        //                    {
        //                        onway19no++;
        //                    }
        //                }


        //            }
        //            else if (onway15no == 0 && onway19no == 1)
        //            {
        //                if (traytype == "C19")
        //                {
        //                    if ((stageno - 1) > 0)
        //                    {
        //                        lp.UpdateTrayForwardByNid(1, nid);
        //                        if (traytype == "C15")
        //                        {
        //                            onway15no++;
        //                        }
        //                        else
        //                        {
        //                            onway19no++;
        //                        }
        //                    }
        //                    else
        //                    {
        //                        lp.UpdateTrayForwardByNid(2, nid);
        //                    }
        //                }
        //                else
        //                {
        //                    lp.UpdateTrayForwardByNid(1, nid);
        //                    if (traytype == "C15")
        //                    {
        //                        onway15no++;
        //                    }
        //                    else
        //                    {
        //                        onway19no++;
        //                    }
        //                }
        //            }
        //            else
        //            {
        //                lp.UpdateTrayForwardByNid(2, nid);
        //            }


        //        }
        //        else if (st1sts != "0001" && st2sts == "0001")
        //        {
        //            bool HadReserved = true;

        //            /*查看是否有与待入库的托盘相同的类型的托盘对应的待搬送的架台被预约，未完成搬送的托盘的类型对应的架台是否和被预约的架台一致，一致的话空闲架台数量不用减1，否则空闲架台减1.
        //             * 例，C19空闲架台是2，如果未完成的任务有2个且都是C19并且2个任务对应的架台都预约，则空闲架台有2个，否则的话空闲架台为1，因为不确定现在
        //             * st2的托盘是否有预约。
        //             * 
        //             * 此判断方法要求如果出现未完成的任务要及时删除，如果未及时删除可能会导致出现空闲架台。如果出现错误的预约，要及时解除预约。
        //            */

        //            //从当前任务表获取未完成的入库任务。
        //            DataTable dtintask = task.GetInVentoryTask();
        //            //DataTable dtreservestage = stageinfo.GetReservedStageLocation();
        //            if (dtintask.Rows.Count > 0)
        //            {
        //                for (int i = 0; i < dtintask.Rows.Count; i++)
        //                {//遍历未完成的任务，看是否都有预约，如果有一个没预约则空闲的架台数量要减1。
        //                    //已经预约的架台号
        //                    string resveredstage = dtintask.Rows[i]["tolocation"].ToString();
        //                    string trayno1 = dtintask.Rows[i]["trayno"].ToString();
        //                    string traytype1 = trayno1.Substring(trayno1.Length - 3, 3);
        //                    //看未完成的任务是否和待进入的托盘类型一致，如果一致的话需要判断是否有预约，否则的话空闲架台数量就是实际架台数量
        //                    if (traytype1 != traytype)
        //                    {
        //                        continue;
        //                    }
        //                    int resstagecount = int.Parse(stageinfo.GetReservedStageCount(resveredstage).ToString());
        //                    if (resstagecount > 0)
        //                    {

        //                    }
        //                    else
        //                    {
        //                        HadReserved = false;
        //                        break;
        //                    }
        //                }
        //                //
        //                if (HadReserved)
        //                {
        //                    //st2的托盘已经预约
        //                    lp.UpdateTrayForwardByNid(1, nid);
        //                    if (traytype == "C15")
        //                    {
        //                        onway15no++;
        //                    }
        //                    else
        //                    {
        //                        onway19no++;
        //                    }
        //                }
        //                else if ((stageno - 1) > 0)
        //                {
        //                    lp.UpdateTrayForwardByNid(1, nid);
        //                    if (traytype == "C15")
        //                    {
        //                        onway15no++;
        //                    }
        //                    else
        //                    {
        //                        onway19no++;
        //                    }
        //                }
        //                else
        //                {
        //                    lp.UpdateTrayForwardByNid(2, nid);
        //                }

        //            }
        //            else
        //            {//st2没有任务，空闲架台数=实际数量-在途即st2的数量
        //                if ((stageno - 1) > 0)
        //                {
        //                    lp.UpdateTrayForwardByNid(1, nid);
        //                    if (traytype == "C15")
        //                    {
        //                        onway15no++;
        //                    }
        //                    else
        //                    {
        //                        onway19no++;
        //                    }
        //                }
        //                else
        //                {
        //                    lp.UpdateTrayForwardByNid(2, nid);
        //                }
        //            }

        //        }
        //        else if (st1sts != "0001" && st2sts != "0001")
        //        {
        //            if (onway15no == 0 && onway19no == 0)
        //            {
        //                lp.UpdateTrayForwardByNid(1, nid);
        //                if (traytype == "C15")
        //                {
        //                    onway15no++;
        //                }
        //                else
        //                {
        //                    onway19no++;
        //                }
        //            }
        //            else
        //            {
        //                lp.UpdateTrayForwardByNid(2, nid);
        //            }
        //        }

        //    }
        //    else
        //    {
        //        lp.UpdateTrayForwardByNid(2, nid);
        //    }

        //}

        private void btreset_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(this, "复位用于堆垛机异常运行时，是否要复位!", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                WriteRightValue4(10, 1, 0);
                WriteRightValue4(100, 1, 0);
                WriteRightValue4(30, 1, 0);
                WriteRightValue4(31, 1, 0);
                WriteRightValue4(32, 1, 0);
                WriteRightValue4(33, 1, 0);
                WriteRightValue4(34, 1, 0);
                WriteRightValue4(35, 1, 0);
                WriteRightValue4(36, 1, 0);
                WriteRightValue4(37, 1, 0);
                WriteRightValue4(10, 1, 0);
                WriteRightValue4(11, 1, 0);
                WriteRightValue4(90, 1, 0);
                WriteRightValue4(91, 1, 0);
                WriteRightValue4(92, 1, 0);
                WriteRightValue4(93, 1, 0);
            }
            else
            {

            }
           
           
        }

        private void 结束代码设定ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormEndCodeSetting fmendcode = new FormEndCodeSetting();
            fmendcode.Show();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (bgmove.IsBusy || bgout.IsBusy || bgin.IsBusy || bgHandOutInventory.IsBusy)
            {
                MessageBox.Show("正在出库！");
                return;
            }

            bgHandOutInventory.RunWorkerAsync();
           
        }

        private void 参数设定ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormArgSetting formarg = new FormArgSetting();
            formarg.Show();
        }

        private void timerAliveSignal_Tick(object sender, EventArgs e)
        {
            timerAliveSignal.Stop();
            bgwAliveSignal.RunWorkerAsync();

        }

        private void bgSynTime_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (!kep.SynchronizeTime())
                {
                    Exceptionlog.InsertException("同步时间异常", "与电源通讯同步系统时间时，电源响应为：erro。");
                    richtbxmsg.AppendText("与电源通讯同步系统时间时，电源响应为：erro\r\n");
                }

            }
            catch (Exception ex)
            {
                Exceptionlog.InsertException(ex);
            }
        }

        private void bgwAliveSignal_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            timerAliveSignal.Start();
        }

        private void bgSynTime_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            timerSynTime.Start();
        }

        private void btclearstage_Click(object sender, EventArgs e)
        {
            string fromx = "";
            string froml = "";
            string fromc = "";
            string stageloc = tbxhandstageloc.Text;
            if (!string.IsNullOrEmpty(stageloc.ToString()))
            {
                fromx = stageloc.Substring(0, 1);
                froml = stageloc.Substring(2, 1);
                fromc = stageloc.Substring(4, 1);
            }
            else
            {
                MessageBox.Show("架台号不能为空");
                return;
            }
            string stagelocation = fromx.PadLeft(3, '0') + froml.PadLeft(3, '0') + fromc.PadLeft(3, '0');
            ClearStageTrayInfoAndDBInfo(stagelocation);
            MessageBox.Show("清除架台托盘信息成功！");
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if ((Control.ModifierKeys & Keys.Alt) != 0 && (Control.ModifierKeys & Keys.Control) != 0 && (Control.ModifierKeys & Keys.Shift) != 0 && e.KeyCode==Keys.D0)
            {
                if (btreset.Visible == true || btclearstage.Visible == true)
                {
                    btreset.Visible = false;
                    btclearstage.Visible = false;
                    btchecklink.Visible = false;
                }
                else
                {
                    btreset.Visible = true;
                    btclearstage.Visible = true;
                    btchecklink.Visible = true;
                }
            }
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            tbl_stageinfoTableAdapter stageinfo = new tbl_stageinfoTableAdapter();
            string stagelocation = tbxhandstageloc.Text.Substring(0, 1).PadLeft(3, '0') + tbxhandstageloc.Text.Substring(2, 1).PadLeft(3, '0') + tbxhandstageloc.Text.Substring(4, 1).PadLeft(3, '0');
            
            bool flag = false;
            int reservecount = int.Parse(stageinfo.GetIfReserved().ToString());
            if (reservecount > 0)
            {
                MessageBox.Show("已经预约过架台，不可重复预约!");
                return;
            }
            if (MessageBox.Show(this, "是否要预约此架台！", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                flag = kep.StageReservation(stagelocation);
                if (flag)
                {
                    richtbxmsg.AppendText("预约" + stagelocation + "架台成功！\r\n");
                }
                else
                {
                    richtbxmsg.AppendText("预约" + stagelocation + "架台失败请重新预约！\r\n");
                }
            }
            else
            {

            }
        }

        private void bt93c_Click(object sender, EventArgs e)
        {
            tbxhandstageloc.Text = lb93sts.Text;
        }

        private void bt92c_Click(object sender, EventArgs e)
        {
            tbxhandstageloc.Text = lb92sts.Text;
            tbxtrayno1.Text = lb92tray.Text;
        }

        

        private void bgHandOutInventory_DoWork(object sender, DoWorkEventArgs e)
        {
            string TrayNo = tbxtrayno1.Text;
            string fromlocation = tbxhandstageloc.Text;
            string fromx=fromlocation.Substring(0,1).PadLeft(3,'0');
            string froml=fromlocation.Substring(2,1).PadLeft(3,'0');
            string fromc=fromlocation.Substring(4,1).PadLeft(3,'0');
            string tolocation = "001009003";
            string tox="001";
            string tol="009";
            string toc="003";
            if (string.IsNullOrEmpty(TrayNo))
            {
                MessageBox.Show("出库托盘号不能为空!");
                return;
            }

            if (string.IsNullOrEmpty(fromlocation))
            {
                MessageBox.Show("出库架台号不能为空!");
                return;
            }
            fromlocation = fromx + froml + fromc;
            HandOutInventoryProcess(TrayNo,fromlocation,fromx,froml,fromc,tolocation,tox,tol,toc,4);
            
        }

        private void listboxstageloc_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            listboxstageloc.ClearSelected();
        }

        private void bgReplyERD_DoWork(object sender, DoWorkEventArgs e)
        {
            richtbxmsg.AppendText("已收到充放电结果\r\n");
            bool flag = kep.StepResult();
            if (flag == true)
            {

            }
            else
            {
                richtbxmsg.AppendText("回复ECS充电完成失败！可能是由于数据解析错误导致的\r\n");
                Log.SystemError.Add("回复ECS充电完成失败！可能是由于数据解析错误导致的");
                Thread.Sleep(500);
            }
        }

        private void bgReplyEPF_DoWork(object sender, DoWorkEventArgs e)
        {
            richtbxmsg.AppendText("已收到充电完成信号\r\n");
            //tbmsg.BackColor = Color.Yellow;
            LoadXMLFile(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase);
            List<string> outInventory = kep.ProcessFinish();

            if (outInventory.Count > 0)
            {
                //生成出库任务
                CreateOutTask(outInventory);


            }
            else
            {
                while (outInventory.Count < 1)
                {
                    outInventory = kep.ProcessFinish();
                }
                richtbxmsg.AppendText("回复充电完成信号异常\r\n");
                Log.SystemError.Add("回复充电完成信号出现异常，可能是网络异常导致的");

                //Thread.Sleep(500);

            }
        }

        private void bgReplyERS_DoWork(object sender, DoWorkEventArgs e)
        {
            List<Dictionary<string, string>> listlocationsts = kep.StageStatusChanged();
            for (int i = 0; i < listlocationsts.Count; i++)
            {
                string stagelocation = listlocationsts[i].Keys.ToList<string>()[0];
                string status = listlocationsts[i].Values.ToList<string>()[0];
                UpdateStageStatus(stagelocation, status);
                listlocationsts.RemoveAt(0);
            }
        }


        
    }
}
